Metadata-Version: 2.5
Name: askre-ai
Version: 0.2.1
Summary: Official Python client for ai.askre.com: run ASKRE's prebuilt AI capabilities from any Python app with one key.
Project-URL: Homepage, https://ai.askre.com
Project-URL: Repository, https://github.com/haja-askre/askre-ai
Author: ASK Real Estate (ASKRE)
License-Expression: MIT
License-File: LICENSE
Keywords: ai,askre,client,sdk
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.9
Provides-Extra: async
Requires-Dist: httpx>=0.23; extra == 'async'
Description-Content-Type: text/markdown

# askre-ai

The official Python client for **ai.askre.com**, ASKRE's central AI hub. Install it, set the
key you were issued, and call the AI capabilities your platform has been given. No model
keys, no prompts, no settings on your side: those live in the hub and take effect on your
next call.

Python 3.9+. The sync client is the standard library only; the async client needs httpx.

```bash
pip install askre-ai              # sync client
pip install "askre-ai[async]"     # adds AsyncAskreAI, for FastAPI and other asyncio apps
```

The same client exists for Node as [`@askre/ai`](https://www.npmjs.com/package/@askre/ai),
with the same calls and the same results.

## Three lines

Set one environment variable, the key issued to your platform in the ai.askre.com console:

```bash
ASKRE_AI_KEY=askre_...
```

```python
from askre_ai import AskreAI, features

ai = AskreAI()                                   # reads ASKRE_AI_KEY (and ASKRE_AI_BASE_URL)
r = features(ai).moderate_message({"text": "Call me on 3312 4455"})

if r["ok"]:
    print(r["output"]["block"], r["output"]["reason"])
else:
    print(r["code"], r["message"])               # e.g. capability_disabled
```

Every call returns `{"ok": True, "output", "runId", "model", "durationMs"}` or
`{"ok": False, "code", "message", "runId", "reachable", "httpStatus"}`. It never raises for a
decision the hub made: `code` tells you what the hub decided and `reachable` tells you whether
it answered at all. Field names match the hub contract and the Node package, in every language.

| `code` | Meaning | What to do |
|---|---|---|
| `invalid_input` | Your input failed the capability's checks | Fix the call |
| `capability_disabled` | The hub has this capability switched off for you | Nothing; it is a decision in the console |
| `needs_approval` | Held for a person in the hub console (HTTP 202; `runId` and `approvalId` come back) | Store the run id and check `get_run(run_id)`: `ok` once approved, `cancelled` with `errorCode` `rejected` or `approval_expired` otherwise; `approval["reason"]` carries the reason |
| `budget_exceeded` | Today's budget for your platform is spent | Park and retry later |
| `not_configured` | The hub has no model key | Tell ASKRE |
| `rate_limited` | Too many calls | Back off |
| `invalid_key` | The key is wrong or revoked | Check the key |
| `unreachable` / `timeout` | The hub did not answer | Retry; your fallback decides |

## Async (FastAPI)

The sync client blocks its thread while it waits for the hub. Inside an async app use
`AsyncAskreAI`: the same calls, awaited. Create one for the process and close it on shutdown,
so connections are reused.

```python
from contextlib import asynccontextmanager
from fastapi import FastAPI
from askre_ai import AsyncAskreAI, features

@asynccontextmanager
async def lifespan(app):
    app.state.ai = AsyncAskreAI()
    yield
    await app.state.ai.aclose()

app = FastAPI(lifespan=lifespan)

@app.post("/messages")
async def post_message(body: dict):
    r = await features(app.state.ai).moderate_message({"text": body["text"]})
    if r["ok"] and r["output"]["block"]:
        return {"blocked": True, "reason": r["output"]["reason"]}
    return {"blocked": False}
```

## The capabilities

One method per prebuilt capability. Your platform may not have all of them enabled;
`ai.capabilities()` lists what you can run.

```python
f = features(ai)

f.moderate_message({"text": text})                          # block / reason / categories / confidence
f.analyse_message({"deal": d, "message": m, "thread": t})   # risk score, safety flags, extracted terms
f.deal_summary({"deal": d, "viewerRole": role, "events": e})  # narrative, open points, last activity
f.terms_sheet({"terms": terms, "notDiscussed": []})         # one neutral paragraph
f.deal_assistant({"messages": messages})                    # the next assistant reply
f.read_contract({"text": text, "focus": "termination"})     # clauses, risks, plain-English summary
f.lead_signal({"items": items})                             # CRM note classifiers, also offer_signal, booking_signal
```

Or call any capability by key:

```python
ai.run("message-moderation", {"text": text})
```

Every call takes the same options: `reference` (your own id for the request, e.g.
`"msg:8891"`, stored on the run and echoed in webhooks), `conversation`
(`{"key": ..., "subjectRef": ...}`, for conversational capabilities only), `timeout`.

## Slow work: queue it

```python
q = ai.enqueue("contract-reading", {"text": contract})
if q["ok"]:
    done = ai.wait_for_run(q["runId"])         # or receive it by webhook
```

## Webhooks

Register a callback URL and secret in the hub console. Every delivery is signed; verify it
against the **raw** body before you trust it.

```python
from askre_ai import read_webhook

@app.post("/askre-webhook")
async def askre_webhook(request: Request):
    delivery = read_webhook(await request.body(), request.headers, os.environ["ASKRE_WEBHOOK_SECRET"])
    if delivery is None:
        return Response(status_code=401)
    # delivery["event"] is run.completed | run.failed | approval.required | approval.decided
    return Response(status_code=204)
```

## Options

```python
AskreAI(
    key=None,                       # default: ASKRE_AI_KEY from the environment
    base_url=None,                  # default: ASKRE_AI_BASE_URL, then https://ai.askre.com
    timeout=20.0,                   # seconds, per request
)
AsyncAskreAI(..., http_client=None)  # optionally your own httpx.AsyncClient
```

`whoami()`, `capabilities()`, `get_run()` and `wait_for_run()` raise `AskreAIError` (with
`code` and `http_status`) when the hub refuses; `run()` and `enqueue()` never do.

## What this package does not do

It does not hold a model key, read your database, or add settings to your app. Which features
you have, whether each is on, which model and prompt it uses, and your limits are all decided
in the ai.askre.com console by ASKRE. If something is switched off, your call tells you so.

## License

MIT, for this client only. The hub behind it, ai.askre.com, is ASKRE's and is not covered by this license.
