Metadata-Version: 2.5
Name: liyaengine
Version: 0.20.0
Summary: Official Python client for the Liya Engine public API
Project-URL: Homepage, https://liyaengine.ai
Project-URL: Documentation, https://liyaengine.ai/docs/sdks/python
Project-URL: Repository, https://github.com/liyaengine/sdk-python
Author-email: Liya Engine <support@liyaengine.ai>
License-Expression: MIT
License-File: LICENSE
Keywords: ai,client,liyaengine,sdk
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1,>=0.27
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Description-Content-Type: text/markdown

# liyaengine

Official Python client for the [Liya Engine](https://liyaengine.ai) public API.

> **Status: early access.** This SDK currently covers Domains, Intents, Collections, Documents, Agents, Workflows, Evaluations, direct intent execution, Guardrail Policies, Prompt Studio, and Traces. More resources ship incrementally — see [Roadmap](#roadmap).

## Install

```bash
pip install liyaengine
```

## Quickstart

```python
from liyaengine import LiyaEngine

client = LiyaEngine(api_key="liya_...")

collection = client.collections.create(
    slug="contracts",
    label="Contracts",
    domain_keys=["legal-ops"],
)

collections = client.collections.list()
```

Or as a context manager (closes the underlying HTTP connection pool automatically):

```python
with LiyaEngine(api_key="liya_...") as client:
    collections = client.collections.list()
```

Get an API key from your [Liya Engine dashboard](https://app.liyaengine.ai) under Settings → API Keys.

## Domains & Intents

A Domain is the top-level container most tenants configure first; Intents live under it.

```python
domain = client.domains.create(domain_key="billing", display_name="Billing")

intent = client.domains.intents.create(
    "billing", intent_key="refund-status", display_name="Refund Status",
    description="Answer refund-status questions.",
    prompt_template="You are a billing assistant. Question: {{message}}",
    # Agent mode, per-intent execution/retrieval/cache overrides — optional:
    agent_config={"enabled": True, "max_steps": 3},
)

one_intent = client.domains.intents.get("billing", "refund-status")

# Every update creates a restorable version snapshot automatically.
versions = client.domains.intents.versions.list("billing", "refund-status")
client.domains.intents.versions.restore("billing", "refund-status", versions[0].version_number)

# Direct retrieval — no LLM call, useful for testing knowledge scoping.
result = client.domains.query("billing", query="refund timeline")
```

> `domains.update()`/`domains.intents.update()` return `{"updated": 1}`, not the updated object — call `get()`/`list()` again for the fresh state. Guardrail policy attachment is still dashboard-only (a separate resource with no `/v1` route yet). To bind an intent's prompt to a Prompt Studio library version instead of inline text, pass `prompt_binding={"kind": "library_version", "prompt_id": ..., "version_id": ..., "content_hash": ...}` in place of `prompt_template` — editing `prompt_template` directly afterward without also passing `prompt_binding` silently detaches the binding.

## Domain Tools

The custom webhook tools an agent-mode intent (`agent_config={"enabled": True, ...}`) can call mid-conversation — e.g. a real order-status lookup against your own backend. Every custom tool is dispatched by one generic platform tool, `webhook_sender`; the LLM calls `webhook_sender({tool_name, payload})`, and `webhook_sender` looks up `tool_name` in the domain's `custom_tools` to find the real endpoint.

```python
# 1. Define the tool on the domain.
client.domains.tools.update(
    "shipping-support",
    # webhook_sender must be explicitly enabled here — defining custom_tools
    # alone does nothing, since it's webhook_sender that actually dispatches them.
    enabled_platform_tools=["webhook_sender"],
    custom_tools=[{
        "name": "lookup_order",
        "display_name": "Order Lookup",
        "description": 'Looks up a real order by number and returns its current status. Call with {"order_number": "..."}.',
        "endpoint_url": "https://fernbankoutdoor.com/api/liya-tools/lookup-order",
        "auth_type": "api_key",
        "auth_value": os.environ["LIYA_TOOL_SHARED_SECRET"],  # write-only — never returned by get()
    }],
)

# 2. Verify the endpoint actually works before wiring it into a live intent.
test_result = client.domains.tools.test("shipping-support", "lookup_order", {"order_number": "A1092"})

# 3. Point the intent at "webhook_sender" — NOT "lookup_order". agent_config["tools"]
# is a platform-tool allowlist; "lookup_order" is only ever an *argument* the
# model passes to webhook_sender at call time, never an entry in this array.
client.domains.intents.update(
    "shipping-support", "track-order",
    agent_config={"enabled": True, "tools": ["webhook_sender"], "max_steps": 3},
)

config = client.domains.tools.get("shipping-support")
# config.custom_tools[0].auth_configured is True — the real credential is never returned, only whether one is set.
```

> **Two real footguns, easy to hit on the first try — both now rejected server-side instead of failing silently:** (1) `enabled_platform_tools` must include `"webhook_sender"` — the API rejects `tools.update()` with `400 WEBHOOK_SENDER_NOT_ENABLED` if you set `custom_tools` without it, since a domain with only `custom_tools` defined and no platform tool enabled would otherwise register *zero* tools and the model would just apologize (or worse, quietly fabricate a plausible-looking answer if your prompt insists it report a result). (2) `agent_config["tools"]` takes platform tool names, so it's `["webhook_sender"]`, never `["lookup_order"]` — the API rejects `intents.create()`/`intents.update()` with `400 INVALID_AGENT_TOOL` if a custom tool's own name appears there, since it's an argument passed to `webhook_sender` at call time, not an allowlist entry. Beyond that: there's no JSON-schema parameter definition for a custom tool today — `description` is the *only* thing the model sees to decide when and how to call it, so be explicit about the fields you expect. `custom_tools` in `update()` REPLACES the entire array, not a per-tool patch. Omit `auth_value` on an update to preserve the existing stored credential; it's encrypted separately and never round-trips back to a reader.

## Run

The primary way to actually invoke an intent — built-in pack or custom domain — and get a real, LLM-generated response back. `agents.run()` and a domain's public `/v1/{domain}/{intent}` route both reach this same endpoint under the hood; call it directly when you don't need an Agent's multi-turn orchestration on top.

```python
result = client.intents.run(
    domain="billing",
    intent="refund-status",
    message="How long do refunds take?",
)

print(result.data)      # shape depends on domain — see docstring
print(result.metadata)  # {"model_used": ..., "tokens_used": ..., "cost_usd": ..., "latency_ms": ..., "cached": ..., ...}
print(result.usage)     # {"requests_remaining": ..., "tokens_remaining": ..., ...}
```

Or stream it token by token:

```python
for event in client.intents.stream(domain="billing", intent="refund-status", message="How long do refunds take?"):
    if event["type"] == "token":
        print(event["delta"], end="", flush=True)
    if event["type"] == "done":
        print("\n", event["session_id"], event["cost_usd"])
    if event["type"] == "error":
        raise RuntimeError(event["message"])
```

> **Streaming works for built-in packs and custom-domain intents.** A custom-domain stream sends a `{"type": "sources"}` event before the first token when retrieval ran, and its `done` event carries `structured`, `confidence`, `blocked` and `stream_mode`. If the intent's guardrail policy needs the whole answer before release (grounding block, structured-output retry), the answer arrives as one `token` event with `done["stream_mode"] == "buffered"`. Pre-flight rejections (feature not enabled, quota) raise a `LiyaEngineAPIError` before any event; once a stream *has* opened, every other failure arrives as an in-band `{"type": "error"}` event, not a raised error — always check `event["type"]` in your loop, not just try/except. Neither method defaults `domain` sensibly if you omit both `domain` and `pack` — it falls back to `"hiring"`, a historical default carried over from the API itself — pass one explicitly.

## Collections

```python
client.collections.list()
client.collections.get(id)
client.collections.create(slug=..., label=...)  # omit domain_keys (or pass []) for a general (domain-less) collection
client.collections.update(id, label=..., tags=[...], visibility=...)
client.collections.delete(id)

# Direct retrieval — no Domain, Intent, or Agent needed at all. Omit
# collection_ids to search every general collection the tenant owns.
result = client.collections.query(query="PTO policy", top_k=5)

# Reference documents into a collection — never copies them, never touches embeddings.
client.collections.documents.attach(collection_id, document_id)
client.collections.documents.list(collection_id)  # returns CollectionDocumentSummary, a narrower shape than Document — see below
client.collections.documents.detach(collection_id, document_id)

# Scope a collection's knowledge to a domain.
client.collections.domains.attach(collection_id, "legal-ops")
client.collections.domains.detach(collection_id, "legal-ops")

# Live aggregation — no rollup table, always reflects current state.
stats = client.collections.analytics(collection_id)

# What references this collection — domains, intents, agents (indirect via
# domain). "workflows" is always None: no workflow-to-collection link exists.
refs = client.collections.connections(collection_id)
```

Full field reference: [Collections API](/docs/api-reference/collections).

## Documents

The tenant-wide knowledge pool collections reference (a document can belong to zero, one, or many collections — attaching never copies it or touches its embeddings).

```python
client.documents.list()
doc = client.documents.get(id)  # includes the full chunk_list
client.documents.delete(id)

# Synchronous — blocks until extraction/chunking/embedding finishes. If
# collection_ids names exactly one collection, that collection's own
# chunking/embedding defaults pre-fill the upload.
uploaded = client.documents.upload(
    file_base64="...",
    file_name="refund-policy.pdf",
    category="policy",
    collection_ids=[collection_id],
)

# Push a URL or inline content — upserts by a deterministic source_id.
client.documents.push(url="https://example.com/faq", title="FAQ")
```

> Unlike `list()`/`get()`, `upload()`'s response has no `uploaded_by` — a real, pre-existing API asymmetry, not an SDK gap. Call `get(id)` afterward if you need it. Similarly, `collections.documents.list()` returns `CollectionDocumentSummary` (`id`/`name`/`chunks`/`size_kb`/`embedding_model`/`uploaded_at` only) rather than a full `Document` — no `category`, `uploaded_by`, or `collections` field; call `documents.get(id)` for the complete record.

For large files or a multi-page crawl, use the async job queue instead — it returns immediately and you poll for completion:

```python
job = client.documents.jobs.create_url_job(url="https://example.com", depth=2)
# ...or: client.documents.jobs.create_file_job(file_base64=..., file_name=...)

status = client.documents.jobs.get(job["jobId"])  # pending | running | completed | failed | cancelled
client.documents.jobs.list(status="running")
client.documents.jobs.cancel(job["jobId"])
```

> Cancellation is cooperative (checked between page fetches / chunk embeds), not instant, and there is no crash-recovery sweep — if the process running a job restarts mid-run, the job is left "running" indefinitely rather than auto-retried. Poll `get(job_id)` for terminal status; don't assume `cancel()` stops it immediately.

### Read a file without storing it

```python
import base64

# Same parser as document uploads; images and scanned PDF pages are
# transcribed through your model routing on paid plans. Nothing is stored.
with open("acord-125.pdf", "rb") as f:
    parsed = client.files.parse(file_name="acord-125.pdf", file_base64=base64.b64encode(f.read()).decode())
# parsed.text, parsed.pages, parsed.warnings, parsed.transcribed_pages
```

### Flagged chunks

A chunk that accumulates enough human corrections (a support agent repeatedly overriding an AI answer that cited it) gets flagged for review — content worth updating or removing. Read/resolve only; whatever caused the flag is product-internal logic with no SDK surface.

```python
flagged = client.documents.list_flagged_chunks()
client.documents.resolve_flagged_chunk(flagged[0].id)
```

## Access control on retrieval

Restrict a document to groups, and tell each request which groups the end user belongs to. Retrieval then returns unrestricted documents plus the ones the user's groups share, on every path (runs, agents, `collections.query`, `domains.query`).

```python
# 1. Label documents (leave out for unrestricted; None clears a label).
client.documents.upload(file_base64=data, file_name="pay-bands.pdf", access_groups=["hr"])
client.documents.set_access(doc_id, ["hr", "finance"])  # relabel, no re-embedding

# 2. Turn enforcement on for the domain.
client.domains.update("hr-assistant", retrieval_access="enforce")

# 3. Send the end user's groups from your server (never from user input).
client.intents.run(
    domain="hr-assistant", intent="answer",
    input={"user_id": "emp_42", "message": "What is the L5 band?"},
    access={"groups": ["hr"]},
)
```

On an enforcing domain, a request with no `access` sees unrestricted documents only. `access` is a top-level field and is never part of the prompt. Groups are your own strings (up to 50 per request, 64 characters each).

## Agents

```python
agent = client.agents.create(
    agent_key="support-triage",
    name="Support Triage",
    goal="Triage incoming support tickets and route them to the right team.",
)

# Agents are created in draft status — deploy to activate for execution.
client.agents.deploy(agent.agent_key)

result = client.agents.run(agent.agent_key, input={"message": "My order hasn't arrived yet."})

history = client.agents.list_runs(agent.agent_key)

# run_stream() — real-time step progress instead of one awaited result.
# Step-level, not token-level: the agent orchestration loop has no
# streaming synthesis call, so there's no token delta to yield. What
# streams is orchestration progress itself — a "step" event the instant
# each llm_call/tool_execution happens — with the complete final answer
# arriving in one "done" event, never token-chunked.
for event in client.agents.run_stream(agent.agent_key, input={"message": "Where is my order?"}):
    if event["type"] == "step":
        print(event["step"]["type"], event["step"].get("tool_name") or event["step"].get("model"))
    elif event["type"] == "done":
        print(event["output"])
    elif event["type"] == "error":
        print(event["code"], event["message"])
```

## Workflows

```python
workflow = client.workflows.create(
    name="Lead Intake",
    steps=[{"step_type": "trigger", "config": {"trigger_subtype": "webhook"}}],
)

# Workflows are created in draft status — deploy to publish and make them
# callable. Deploying a webhook-triggered workflow for the first time mints
# its webhook secret; capture it immediately, it is never returned again.
deployed = client.workflows.deploy(workflow.workflow_key)
webhook_url, webhook_secret = deployed["webhook_url"], deployed["webhook_secret"]

# Roll the secret with a grace window so in-flight senders don't break.
client.workflows.rotate_webhook_secret(workflow.workflow_key, grace_period_seconds=300)

# Flip a deployed workflow on/off without touching its definition.
client.workflows.toggle(workflow.workflow_key)

result = client.workflows.run(workflow.workflow_key, input={"email": "ada@example.com"})

history = client.workflows.list_runs(workflow.workflow_key)

# run_stream() — real-time step progress, same step-level-not-token-level
# reasoning as agents.run_stream(): no step type in a Workflow streams
# tokens, so a "step" event fires as each one is traced, and "done" carries
# the complete trace in one piece.
for event in client.workflows.run_stream(workflow.workflow_key, input={"email": "ada@example.com"}):
    if event["type"] == "step":
        print(event["step"]["stepType"], event["step"]["success"])
    elif event["type"] == "done":
        print(event["status"], event["trace"])
```

> `deploy()` and `rotate_webhook_secret()` return the plaintext webhook secret exactly once. Store it immediately — subsequent reads (`get`, `list`) only ever expose `trigger_config["has_secret"]`.

### Files in a run

```python
# Up to 10 files, 18 MB per run. The API reads each one before the run
# starts and adds attachment_texts and attachments_text to the run input,
# so an intent step can map {{trigger.attachments_text}}. The bytes are
# never stored.
client.workflows.run("submission-triage", input={
    "email_text": "Please quote the attached risk.",
    "attachments": [{"file_name": "acord-125.pdf", "file_base64": pdf_base64}],
})
```

### Scheduled and event triggers

```python
# Every weekday at 07:00 Chicago time, with static input for each run.
client.workflows.create(name="Daily regulatory digest", steps=[
    {"step_type": "trigger", "config": {"trigger_subtype": "schedule", "cron": "0 7 * * 1-5", "timezone": "America/Chicago", "input": {"region": "US"}}},
    # ...
])

# Whenever a document lands in a collection.
client.workflows.create(name="Map new regulation to policies", steps=[
    {"step_type": "trigger", "config": {"trigger_subtype": "event", "event_type": "document.ingested", "filter": {"collection_id": "col_123"}}},
    # ...
])

catalog = client.workflows.trigger_catalog()  # event types + allowed filters
```

Schedules start when the workflow is deployed and run at most every 5 minutes; missed slots during downtime aren't replayed. Event payload fields reach steps as `{{trigger.*}}`, plus `{{trigger.event_id}}` for de-duplicating actions. A workflow never receives its own `workflow.*` events, and event chains stop after 3 hops.

### Approval steps

An `approval` step pauses the run (`status == "awaiting_approval"`, with `approval_id`) until someone decides. Approve continues down the step's success branch; reject follows its failure branch, or ends the run as `"rejected"`.

```python
run = client.workflows.run("refunds", input={"order_id": "1042", "amount": 120})
if run["status"] == "awaiting_approval":
    # e.g. from a Slack button handler — decided_by names the person in the audit log
    result = client.workflows.approvals.decide(run["approval_id"], decision="approve", note="Within policy", decided_by="jane@acme.com")
    print(result["run"]["status"])  # "completed", or "awaiting_approval" for a second approval step

waiting = client.workflows.approvals.list(status="pending")
```

## Evaluations

A Suite binds a Dataset to one specific intent; `suites.run()` calls that intent for real and scores what it produces. `runs.submit()`/`evaluations.score()` score a response you already generated yourself — no intent execution involved.

```python
dataset = client.evaluations.datasets.create(
    name="Support Replies",
    cases=[{"input": {"message": "Where is my order?"}}],
)

suite = client.evaluations.suites.create(
    name="Order Status Suite",
    domain_key="support",
    intent_key="order-status",
    dataset_id=dataset.id,
)

# Runs are always async — poll for status/results.
run = client.evaluations.suites.run(suite.id)
result = client.evaluations.runs.get(run.id)

# A failed run can be resumed — already-scored cases are skipped.
client.evaluations.runs.resume(run.id)

# Score a response you already generated, no dataset/suite required.
scored = client.evaluations.score(
    input={"message": "Where is my order?"},
    output="Your order shipped yesterday and should arrive by Friday.",
)
```

> `custom_scorer_webhook_secret` on a Suite is write-only — it's never returned; only a `custom_scorer_webhook_secret_set` boolean comes back on reads.

### Release gate — the CI-facing endpoint

A suite can carry a `gate_policy` — thresholds a run must clear (pass rate, mean score, or a plain pass/fail outcome). `check_gate()` is the call a CI pipeline step actually wants: it triggers a real run and blocks until the gate resolves, so you get a synchronous pass/fail instead of hand-rolling run-then-poll logic yourself.

```python
client.evaluations.suites.update(
    suite.id,
    gate_policy={"schema_version": 1, "require_passed_outcome": True, "min_pass_rate": 0.8},
)

# Blocks (default up to 60s, capped at 280s) until the gate resolves.
gate = client.evaluations.suites.check_gate(suite.id, max_wait_seconds=90)

if gate.timed_out:
    # Took longer than max_wait_seconds — poll runs.get(gate.run_id) yourself from here,
    # don't call check_gate() again (that starts a second run).
    pass
elif gate.gate_decision == "failed":
    print("Release blocked:", gate.gate_failure_reasons)
    sys.exit(1)

# A cheap read of the last finished run's result, without triggering a new one.
status = client.evaluations.suites.get_gate(suite.id)
```

A suite with no `gate_policy` always resolves `gate_decision: "not_configured"` — it never blocks a pipeline on its own until you set one.

## Guardrail Policies

The tenant-configurable safety config that replaces a single hardcoded, global pipeline every tenant used to share identically — PII detection, content policy, schema/action validation, and hallucination checks, all tunable per policy. Every tenant always has exactly one `is_default` policy; a domain/intent/agent/action with no policy attached falls through to it.

```python
strict = client.guardrail_policies.create(
    name="Strict — Billing",
    config={
        "pre_llm": {"pii": {"enabled": True, "mode": "redact"}},
        "post_llm": {"hallucination_check": {"enabled": True}},
    },
)

# attach()/detach() is the ONLY way to set a consumer's guardrail_policy_id —
# it's not a parameter on that consumer's own create()/update() call.
client.guardrail_policies.attach(strict.id, "agent", copilot.id)

# Dry-run a saved policy or an unsaved draft config against real content
# before wiring it in — runs the actual pipeline, same stages a live
# request would hit.
check = client.guardrail_policies.test(
    policy_id=strict.id,
    stage="pre_llm",
    content="My email is jane@example.com, please refund my order.",
)
print(check.passed, check.content)  # False, redacted content

# Check-volume analytics and version history come with every policy.
stats = client.guardrail_policies.analytics(strict.id, days=30)
versions = client.guardrail_policies.versions.list(strict.id)
```

> The platform's ML classifier (for injection detection and grounding/hallucination checks) isn't a field on `config` — it's an infrastructure capability that activates automatically whenever it's configured tenant-wide, layered on top of `content_policy.injection_detection` and `post_llm.hallucination_check`. There's nothing to toggle for it specifically.

## Prompt Studio

A versioned, immutably-pinned prompt library. A prompt's content only ever changes by adding a new version — never by editing one in place — and `publish()` promotes one exact version to the tenant's production pointer. AI-authoring (draft/improve a prompt with Prompt Copilot) is dashboard-only; this SDK covers list/get/create + versioning + publish.

```python
# Creates the prompt AND its immutable version 1 in one call.
prompt = client.prompts.create(
    prompt_key="refund-policy",
    name="Refund Policy",
    content="Answer {{question}} using only the approved refund policy below.",
    variables=[{"name": "question", "type": "string", "required": True}],
)

# Content only changes by adding a new version — never in place.
v2 = client.prompts.versions.create(
    prompt.id,
    content="Answer {{question}} using only the approved refund policy below. Always cite the clause.",
)

# Publishing promotes one exact version to production — existing consumers
# bound via prompt_binding stay pinned to their own version until repointed.
client.prompts.publish(prompt.id, version_id=v2.id)

# Bind an intent's prompt to this library version instead of inline text.
client.domains.intents.update(
    "billing", "refund-status",
    prompt_binding={"kind": "library_version", "prompt_id": prompt.id, "version_id": v2.id, "content_hash": v2.content_hash},
)
```

> Editing `prompt_template` directly on a bound intent afterward, without also passing `prompt_binding`, silently detaches the binding — see the Domains & Intents section above.

## Traces

Read-only access to execution traces — the same data and filters as the dashboard's Trace Explorer. Requires a secret API key: a trace holds prompts and responses, so public embed tokens are refused (`EMBED_TOKEN_NOT_ALLOWED`). Comments, bookmarks and replay stay in the dashboard.

```python
from datetime import datetime, timezone

# Flagged calls in a domain over a window, slowest first.
page = client.traces.list(
    domain="support",
    flagged=True,
    from_=datetime(2026, 10, 1, tzinfo=timezone.utc),
    sort="latency",
    limit=50,
)
page.pagination  # {"total": ..., "limit": 50, "offset": 0}

# The full trace for a request. The id is the message_id that run() returned.
trace = client.traces.get(page.traces[0].trace_id)
trace.retrieved_context  # every retrieved chunk with its source and similarity score
trace.observations       # the trace as a tree of steps with timing

# One row per request, agent run or workflow run, with what each run started nested inside.
client.traces.list(scope="traces", kind="workflow", nested=True)

# An agent or workflow run's steps.
client.traces.get_run("agent", "run_123")

# Totals over every trace matching the filters, not just a page.
stats = client.traces.stats(domain="support")  # defaults to the last 30 days
stats.latency_ms["p95"]
stats.issues_by_category
```

Filters: `domain`, `intent`, `flagged`, `issue` (`"safety"`, `"validation"`, `"grounding"`, `"other"`), `from_`, `to`, `user_id`, `session_id`, `model`, `min_latency_ms`, `from_cache`, `capture`, `q`, plus `limit`, `offset`, `sort` and `order`. Traces are retained for the period your plan includes.

## Error handling

Every failed request raises `LiyaEngineAPIError`, carrying the API's `code`, `message`, and HTTP `status`:

```python
from liyaengine import LiyaEngineAPIError

try:
    client.collections.create(slug="contracts", label="Contracts", domain_keys=["legal-ops"])
except LiyaEngineAPIError as err:
    if err.code == "SLUG_CONFLICT":
        # handle the conflict
        pass
    raise
```

Network failures and timeouts raise `LiyaEngineNetworkError` instead. Requests are retried automatically on `429`/`5xx` responses and transient network errors (2 retries by default).

## Configuration

```python
LiyaEngine(
    api_key="liya_...",
    base_url="https://api.liyaengine.ai",  # override for local/staging
    timeout_s=30.0,
    max_retries=2,
)
```

## Roadmap

- [x] Domains & Intents (full CRUD parity with the dashboard, prompt binding, agent/execution/retrieval/cache config, versioning, direct retrieval query, narrow document upload — guardrail policy attachment via `guardrail_policies.attach()`)
- [x] Collections
- [x] Agents (full CRUD, deploy, run, run/session history, real-time step streaming via `run_stream()`)
- [x] Workflows (full CRUD, toggle, deploy, webhook secret rotate, run, run history, real-time step streaming via `run_stream()`, schedule and event triggers, approval steps)
- [x] Evaluations (Datasets/Cases/Suites/Runs/Reviews CRUD, suite execution, cancel/resume, statistical + pairwise compare, standalone scoring, CI-facing release gate)
- [x] Full KBaaS (document list/get/delete/upload/push, async ingestion jobs + URL crawl, collection↔document/domain attach-detach, analytics/connections)
- [x] Run / Run (streaming) — built-in packs and custom-domain intents
- [x] Domain agentic tool configuration (previously dashboard-only)
- [x] Guardrail Policies (full CRUD, attach/detach, live test console, versioning, analytics — previously dashboard-only)
- [x] Flagged-chunk review (read/resolve — the corrections that cause a flag are dashboard-only, product-internal logic)
- [x] Traces (list/filter, get one, agent and workflow run traces, statistics — read-only; comments, bookmarks and replay stay dashboard-only)
- [x] Prompt Studio (list/get/create + versioning + publish — AI-authoring stays dashboard-only)
- [ ] Async client

Full docs: https://liyaengine.ai/docs/sdks/python

## Development

```bash
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
mypy src
pytest
```

## License

MIT
