Metadata-Version: 2.4
Name: solveq-ai
Version: 0.1.0
Summary: Source-agnostic AI enrichment for civic complaints — category, district, sentiment, urgency, SLA
Author-email: SolveQ <korkrit.p@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/AttaliZ/solveq-ai
Project-URL: Repository, https://github.com/AttaliZ/solveq-ai
Project-URL: Issues, https://github.com/AttaliZ/solveq-ai/issues
Keywords: nlp,thai,civic-tech,geocoding,llm,triage
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.28.1
Requires-Dist: pydantic>=2.9
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
Requires-Dist: respx>=0.22; extra == "dev"
Requires-Dist: mypy>=1.11; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Dynamic: license-file

# solveq-ai

Source-agnostic AI enrichment for civic complaints.

Give it **text** and optionally a **point on a map**. Get back a category, a
district, sentiment, an urgency score and an SLA assessment — as a strictly
typed object that is **always complete**, whether or not anything upstream
worked.

```python
from solveq_ai import SolveqAI

sdk = SolveqAI(api_key="...", llm="typhoon")

result = await sdk.enrich("ไฟถนนดับทั้งซอย", location=(13.7524, 100.5017))

result.category        # "ไฟฟ้า"
result.district        # "พระนคร"
result.sentiment       # "negative"
result.urgency         # 0.7
result.sla.severity    # "high"
result.sla.due_hours   # 18.0
result.ok              # True — nothing fell back
```

## Why it exists

The category and district logic used to live in two places at once. SolveqOA
called Typhoon for a category and Nominatim for a district; CDG-HAT-2026 called
Typhoon *again* for sentiment, urgency and a summary. Two HTTP clients, two
retry policies, two incompatible ideas of what to do when the model is down —
against one provider, for one complaint.

This package is the single copy. Both apps now make one call each, and the
prompt, the vocabulary, the fallbacks and the rate limiting have one home.

## Install

```bash
uv pip install -e /var/www/solveq-ai          # local path, during development
```

Or as a dependency:

```toml
dependencies = ["solveq-ai @ file:///var/www/solveq-ai"]
```

Runtime dependencies are `httpx` and `pydantic` only. The vendor SDKs
(`openai`, `anthropic`) are deliberately **not** required — every provider we
speak to is a single JSON POST, and pulling two large SDKs to reach two URLs
would make this package heavier than both callers combined.

## Using it from your own system

Nothing in this package knows about LINE, LIFF, tickets, or either of the
services it was extracted from. If you run a complaint intake of any shape —
a web form, a call-centre CRM, a batch importer — it takes the two facts you
already have.

```python
import asyncio
from solveq_ai import SolveqAI

sdk = SolveqAI(api_key="sk-...", llm="typhoon")

async def triage(complaint_text: str, lat: float, lon: float) -> dict:
    result = await sdk.enrich(complaint_text, location=(lat, lon))
    return {
        "category": result.category,
        "district": result.district_or_none,   # None, not a placeholder
        "urgency": result.urgency,
        "severity": result.sla.severity,
        "due_in_hours": result.sla.due_hours,
        "trustworthy": result.ok,              # False -> some of this is a fallback
    }

print(asyncio.run(triage("ไฟถนนดับทั้งซอย", 13.7524, 100.5017)))
```

Not running async? There is a blocking wrapper:

```python
result = sdk.enrich_sync("ท่อประปาแตก น้ำท่วมถนน")
```

It refuses to run inside a live event loop rather than deadlocking on it — that
mistake otherwise produces a hang with no traceback.

### Bring your own categories

`DEFAULT_CATEGORIES` is *our* vocabulary, taken from values that exist in our
database. Yours will differ, and the model must only ever answer from your list:

```python
sdk = SolveqAI(
    api_key="sk-...",
    categories=("ถนน", "ไฟฟ้า", "ประปา", "ขยะ", "สัตว์จรจัด"),
)
```

Anything the model returns outside that tuple is rejected and reported as a
degradation — it is never stored. That matters more than it sounds: a model
answering with a phrase instead of a category creates a new group of one in
whatever dashboard consumes the output, with no error anywhere.

### Handling a degraded answer

The whole point of the design is that you *can* ignore this — `result.category`
is always a usable string. But when it matters:

```python
result = await sdk.enrich(text)

if not result.ok:
    for problem in result.degraded:
        log.warning("enrichment fell back at %s: %s", problem.stage, problem.reason)

# Persisting to a nullable column? Use the _or_none accessors, or you will
# write the literal string "ไม่ระบุเขต" as if it were a real district.
row.district = result.district_or_none
row.category = result.category_or_none
```

### Running without an LLM at all

An empty API key is a supported configuration, not an error. The geocoder still
resolves districts and the keyword lexicon still scores urgency, so you get a
working, visibly-degraded pipeline rather than a crash:

```python
sdk = SolveqAI(api_key="")   # logs a warning, then runs
```

### Swapping the provider or the geocoder

Both are protocols. Anything with the right shape works — which is also how the
test suite avoids the network:

```python
class MyGeocoder:
    name = "internal-gis"

    async def district(self, lat: float, lon: float, *, timeout: float) -> str | None:
        ...  # your own service

sdk = SolveqAI(api_key="sk-...", geocoder=MyGeocoder())
```

## The one guarantee

**`enrich()` does not raise.** Both callers invoke it from a path where an
exception costs more than a wrong answer: in the LINE bot the case is already
committed and the citizen already holds a case number; in the CDG backend the
ticket row is already written. A crash there loses the enrichment *and*
corrupts the flow around it. A fallback loses only the enrichment.

When something fails you still get a full `EnrichmentResult`:

| Field | Fallback |
|---|---|
| `category` | `"ไม่ระบุประเภท"` (`UNKNOWN_CATEGORY`) |
| `district` | `"ไม่ระบุเขต"` (`UNKNOWN_DISTRICT`) |
| `sentiment` | `"neutral"` |
| `urgency` | keyword score from `lexicon.py` — *not* a flat constant |
| `summary` | `""` |

Urgency falls back to keyword scoring rather than a fixed number on purpose. A
flat default would flatten the exact signal the officer queue sorts on, so
during an outage a fire would rank level with a grass-cutting request.

The only thing that *does* raise is programmer error — an unknown provider
name, a malformed SLA policy, or blank input. Those cannot be recovered from at
runtime and failing loudly is how you find them.

### Telling a real answer from a fallback

`category` and `district` are never `None`, so the happy path needs no guards.
When you must not persist a placeholder, read the provenance flags:

```python
result.category_resolved   # False -> category is the fallback constant
result.district_resolved   # False -> district is the fallback constant
result.urgency_source      # "llm" | "lexicon" | "default"
result.degraded            # (Degradation(stage="llm", reason="..."), ...)
result.ok                  # True when degraded is empty

result.district_or_none    # None instead of "ไม่ระบุเขต"
result.category_or_none    # None instead of "ไม่ระบุประเภท"
```

Use `district_or_none` when writing to `cases.district` or `tickets.district`.
Both columns are nullable and their queries depend on that; storing
`"ไม่ระบุเขต"` would create a district nobody owns, and the LINE bot would tell
a citizen *"no officer covers เขตไม่ระบุเขต"*.

## Switching models

```python
SolveqAI(api_key=k, llm="typhoon")                      # default
SolveqAI(api_key=k, llm="gpt-4o")                       # alias for "openai"
SolveqAI(api_key=k, llm="claude")                       # alias for "anthropic"
SolveqAI(api_key=k, llm="openai", model="gpt-4o-mini")  # pin a specific model
SolveqAI(api_key=k, llm="typhoon", base_url="http://gateway.internal/v1")
```

> **Verification status.** Only the Typhoon adapter has been exercised against a
> live endpoint. The OpenAI and Anthropic adapters are fully implemented and
> unit-tested against mocked transports that assert each vendor's documented
> wire format — but the first real call against either is unproven. Test with a
> real key before relying on them in production.

## Tuning SLA thresholds

```python
from solveq_ai import SLAPolicy, SolveqAI

sdk = SolveqAI(
    api_key=k,
    sla_policy=SLAPolicy(
        horizon_hours=24.0,   # tighten the whole clock
        critical_at=0.85,     # urgency at/above this is critical
        high_at=0.65,
        medium_at=0.35,
    ),
)
```

Deadlines are a fraction of the horizon per severity — critical gets 1/12
(6 h against the 72 h default), high a quarter, medium a half, low the whole
horizon. Thresholds must strictly descend; an unordered policy raises at
construction rather than leaving a band silently unreachable.

`horizon_hours` **must match** the `--sla-horizon-hours` the CDG champion model
was trained with and the horizon the dashboard prints. If the three drift
apart, the number on screen answers a different question than the one the model
was asked.

## Configuration reference

| Parameter | Default | Meaning |
|---|---|---|
| `api_key` | `""` | Empty is valid — disables the LLM stage and runs degraded |
| `llm` | `"typhoon"` | `typhoon`, `openai`/`gpt-4o`, `anthropic`/`claude` |
| `model` | per provider | Override the model id |
| `base_url` | per provider | Point at a proxy or gateway |
| `categories` | `DEFAULT_CATEGORIES` | The 18-item vocabulary; a contract, not a suggestion |
| `sla_policy` | `SLAPolicy()` | Severity thresholds and deadlines |
| `timeouts` | `Timeouts()` | `llm=8s`, `geocode=3s`, `total=15s` |
| `provider` | — | Inject a custom `LLMProvider` (used by tests) |
| `geocoder` | `NominatimGeocoder()` | Inject a custom `Geocoder` |
| `enable_geocoding` | `True` | `False` skips district lookup entirely |

The SDK **reads no environment variables**. Both consuming apps have their own
settings layer, and a library that reaches for the environment behind their
back behaves differently in a test than in production for reasons the caller
cannot see. Pass everything in.

## The category vocabulary

`DEFAULT_CATEGORIES` holds 18 single nouns copied from values that already
exist in the CDG `tickets` table — never invented. The dashboard groups on this
value verbatim, so a phrase like `"ถนนชำรุด"` becomes a 19th group holding one
ticket, with no error anywhere. When Traffy adds a type, re-run
`select category, count(*) from tickets group by 1` and replace the set.

## Rate limits

Nominatim allows **one request per second** and requires a contactable
User-Agent. Exceeding it gets the host's IP banned, which breaks every lookup on
the box rather than just this feature. `NominatimGeocoder` enforces the pacing
in-process behind a lock, and caches results for the life of the process keyed
to ~11 m, so repeated reports of the same pothole cost one upstream call.

## Development

```bash
cd /var/www/solveq-ai
uv venv && uv pip install -e ".[dev]"
.venv/bin/python -m pytest -q
```

No test touches the network. Every provider and geocoder is driven through an
`httpx.MockTransport`, so the suite is deterministic and safe to run on a
machine holding live keys.
