Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(llms): add TypeSafe Jev decision provider (#1677)

csy203240ef39f7ac
diff --git a/docs/guides/llm-integrations.md b/docs/guides/llm-integrations.md
index 8b6fd62d..106297b3 100644
--- a/docs/guides/llm-integrations.md
+++ b/docs/guides/llm-integrations.md
@@ -1,15 +1,15 @@
---
title: "LLM Integrations"
-description: "Connect Semantica to Groq, OpenAI, Anthropic, HuggingFace, Novita AI, and 100+ LLM providers through a unified interface."
+description: "Connect Semantica to generative LLM providers and TypeSafe Jev typed decisions."
---
-Semantica exposes a unified provider interface — the same `.generate()`, `.generate_structured()` and `.generate_typed()` methods — across Groq, OpenAI, Anthropic Claude, HuggingFace, Novita AI, and 100+ providers via LiteLLM. Use it when you need to swap providers for latency, accuracy, cost, or data-residency reasons without touching application code.
+Semantica exposes a unified generation interface — the same `.generate()`, `.generate_structured()` and `.generate_typed()` methods — across Groq, OpenAI, Anthropic Claude, HuggingFace, Novita AI, and 100+ providers via LiteLLM. It also provides a deliberately separate decision-only interface for TypeSafe Jev, whose typed Choice, Noul, and Score results are not text generations.
## What Are LLM Integrations?
-The `semantica.llms` module provides a unified interface for connecting to Large Language Model providers. Instead of learning different APIs for each provider, you use the same methods (`.generate()`, `.generate_structured()`, `.generate_typed()`) regardless of whether you're calling Groq, OpenAI, Anthropic, or local HuggingFace models.
+The `semantica.llms` module provides a unified interface for connecting to Large Language Model providers. Instead of learning different APIs for each generative provider, you use the same methods (`.generate()`, `.generate_structured()`, `.generate_typed()`) regardless of whether you're calling Groq, OpenAI, Anthropic, or local HuggingFace models. TypeSafe Jev is the decision-only exception: it exposes `.decide()` because it returns typed decisions rather than generated text.
-**Unified interface across providers:** All LLM providers in Semantica expose identical methods, so switching from OpenAI to Anthropic requires changing only the provider constructor, not your application code.
+**Unified interface across generative providers:** Generative LLM providers in Semantica expose identical methods, so switching from OpenAI to Anthropic requires changing only the provider constructor, not your application code. Jev remains separate so its calibrated probabilities and strict decision types are not flattened into a chat-completion response.
**Provider wrappers vs semantic extraction provider strings:** The `semantica.llms` classes (`Groq`, `OpenAI`, `LiteLLM`, `HuggingFaceLLM`) are Python objects for text generation. The `semantica.semantic_extract` module accepts provider names as strings for entity and relationship extraction. Both approaches are covered in this guide.
@@ -51,7 +51,7 @@ The `semantica.llms` module provides a unified interface for connecting to Large
- Tasks where explainability requires transparent rule-based logic
<Info>
- The providers in `semantica.llms` (`Groq`, `OpenAI`, `LiteLLM`, `HuggingFaceLLM`) are for text generation and `query_with_reasoning()`. For structured entity and relation extraction, `semantica.semantic_extract` accepts provider names as strings. Both patterns are covered here.
+ Generative providers in `semantica.llms` (`Groq`, `OpenAI`, `LiteLLM`, `HuggingFaceLLM`) are for text generation and `query_with_reasoning()`. `Jev` and `AsyncJev` are decision-only and are not drop-in `llm_provider=` values. For structured entity and relation extraction, `semantica.semantic_extract` accepts provider names as strings.
</Info>
## Choosing a Provider
@@ -68,9 +68,9 @@ Four factors drive provider selection, each optimized for different use cases:
The unified interface means you can prototype with Groq for speed, validate accuracy with Claude, and deploy to Azure OpenAI for compliance — without changing application code.
-## The Shared Interface
+## The Shared Generation Interface
-Every provider exposes the same methods:
+Every generative provider exposes the same methods:
```python
provider.generate(prompt: str, **kwargs) -> str
@@ -81,7 +81,103 @@ provider.is_available() -> bool
`generate()` returns a plain string. `generate_structured()` instructs the model to respond in JSON and returns the parsed result — a `dict` for a top-level JSON object, or a `list` if the model returns a top-level JSON array. `generate_typed()` takes a Pydantic model, validates the model's output against it, and retries up to `max_retries` times with the validation error fed back into the prompt — reach for it when downstream code needs a guaranteed shape rather than best-effort JSON. `is_available()` lets you health-check the provider before committing to a call — useful in retry logic and warm-up checks.
-This means every place in Semantica that accepts an LLM — `query_with_reasoning()`, semantic extraction, custom reasoning loops — accepts any of these providers interchangeably.
+This means every place in Semantica that accepts a generative LLM — `query_with_reasoning()`, semantic extraction, custom reasoning loops — accepts any of these providers interchangeably. Jev is not part of this interface because it never returns free text.
+
+## Jev — Typed Decisions for Low-Latency Routing
+
+**TypeSafe Jev** is a System One model for typed decisions over application state. Use it for bounded routing, classification, binary checks, or scoring when the valid outcomes are known in advance. Use a chat LLM instead when the task needs an explanation, synthesis, open-ended text, or multi-step reasoning.
+
+<Warning>
+ Jev is an experimental, early-access provider. Pin and test the SDK version used by your deployment, choose confidence thresholds for your domain, and keep a human or reasoning-model escalation path for high-impact decisions.
+</Warning>
+
+<Warning>
+ TypeSafe SDK 0.7 wire logs include complete request and response bodies at `DEBUG`. Because `state` can contain financial, security, or personal data, keep the `typesafe_sdk` logger at `INFO` or higher in sensitive deployments. Setting the root logger to `DEBUG` can also expose these bodies unless the SDK logger has an explicit higher level.
+</Warning>
+
+```python
+import logging
+
+logging.getLogger("typesafe_sdk").setLevel(logging.INFO)
+```
+
+Install the optional dependency on Python 3.10 or newer:
+
+```bash
+pip install "semantica[llm-typesafe]"
+```
+
+Set `TYPESAFE_API_KEY`, or pass `api_key=` explicitly:
+
+```python
+from semantica.llms import Jev
+
+jev = Jev(model="jev-latest") # reads TYPESAFE_API_KEY
+
+result = jev.decide(
+ state={
+ "amount_usd": 12_500,
+ "destination_country": "US",
+ "policy_flags": [],
+ },
+ question="How should this transaction be routed?",
+ kind="choice",
+ choices={
+ "approve": "All automatic-approval requirements are met.",
+ "escalate": "A person must review the transaction.",
+ },
+)
+
+print(result.value) # "approve" or "escalate"
+print(result.confidence) # routing certainty
+print(result.probabilities) # full Choice distribution
+print(result.request_id) # retain for audit/support correlation
+```
+
+The three decision kinds have intentionally different result semantics:
+
+| Kind | Input criteria | `result.value` | Confidence semantics |
+| :--- | :--- | :--- | :--- |
+| Choice | Choice labels, optionally with descriptions | Selected label | SDK-provided confidence |
+| Noul | Optional `true` and `false` descriptions | Boolean using the 0.5 boundary | `abs(2 * probability - 1)`; `result.probability` preserves the raw probability of yes |
+| Score | Ordered rubric levels | Probability-weighted numeric score | SDK-provided confidence; the full distribution and legend are preserved |
+
+Semantica owns the reasoning, policy checks, escalation, and provenance around the decision. The provider does not silently call a fallback model:
+
+```python
+from semantica.context import ContextGraph
+
+graph = ContextGraph()
+threshold = 0.85
+
+if result.confidence < threshold:
+ route = "human_review" # or invoke a reasoning LLM in caller code
+else:
+ route = str(result.value)
+
+decision_id = graph.record_decision(
+ category="transaction_routing",
+ scenario="Route wire transfer after evidence and policy evaluation",
+ reasoning="Semantica policy checks completed before the Jev routing step.",
+ outcome=route,
+ confidence=result.confidence,
+ decision_maker="jev:{}".format(result.model),
+ metadata={"typesafe_jev": result.to_dict()},
+)
+```
+
+For asynchronous applications, use `AsyncJev` with the same arguments and result type:
+
+```python
+from semantica.llms import AsyncJev
+
+async with AsyncJev() as jev:
+ result = await jev.decide(
+ state="The transaction was submitted from a known device.",
+ question="Does this transaction require manual review?",
+ kind="noul",
+ )
+```
## Groq — Fast Inference for Real-Time Agents
@@ -535,10 +631,10 @@ context.save("./classified_output/q4_analysis/")
</Tab>
<Tab title="Security — SOC/Incident">
-A SOC pipeline uses two providers at different tiers: Groq for sub-500ms initial triage that keeps the analyst in flow, and Anthropic Claude for deep ATT&CK analysis when Tier 1 confidence falls below the escalation threshold. The provider switch is determined programmatically — no manual handoff required.
+A SOC pipeline uses Semantica to collect the alert and applicable runbook evidence, Jev for the bounded Tier 1 routing decision, and Anthropic Claude for deep ATT&CK analysis when Jev is uncertain. The escalation policy stays in caller code; Jev never invokes the fallback itself.
```python
-from semantica.llms import Groq, LiteLLM
+from semantica.llms import Jev, LiteLLM
from semantica.context import AgentContext, ContextGraph
from semantica.vector_store import VectorStore
@@ -551,12 +647,13 @@ context = AgentContext(
decision_tracking=True,
)
-# Preload MITRE ATT&CK runbook knowledge
-context.store([
+# Preload MITRE ATT&CK runbook evidence
+runbook = [
"T1087.002 (Domain Account Discovery): anomalous LDAP enumeration — isolate source host, reset service account passwords",
"T1053.005 (Scheduled Task/Job): encoded PowerShell via wmiprvse.exe — collect task XML, check persistence keys, notify IR",
"T1021.002 (SMB/Windows Admin Shares): PsExec lateral movement to DC — immediate host isolation, reset service accounts",
-])
+]
+context.store(runbook)
alert = (
"SIEM Alert: host ws-finance-03, user jsmith — scheduled task with base64-encoded PowerShell. "
@@ -564,17 +661,22 @@ alert = (
)
context.store(alert, metadata={"type": "alert", "severity": "high"})
-# Tier 1: fast triage with Groq — target < 500ms end-to-end
-fast_llm = Groq(model="llama-3.1-8b-instant", api_key="YOUR_GROQ_KEY")
-triage = context.query_with_reasoning(
- "Is this alert a true positive? One sentence verdict and confidence.",
- llm_provider=fast_llm,
- max_results=5,
-)
-print("TRIAGE: {} (conf={:.0%})".format(triage["response"], triage["confidence"]))
-
-# Tier 2: escalate to Claude for deep analysis if Tier 1 is uncertain
-if triage["confidence"] < 0.88:
+# Tier 1: a bounded Jev decision over the alert and policy/runbook state
+fast_decider = Jev(model="jev-latest") # reads TYPESAFE_API_KEY
+triage = fast_decider.decide(
+ state={"alert": alert, "applicable_runbook": runbook[1]},
+ question="How should the SOC route this alert?",
+ kind="choice",
+ choices={
+ "true_positive": "Evidence strongly matches malicious scheduled-task activity.",
+ "benign": "Evidence supports an authorized administrative action.",
+ "escalate": "Evidence is insufficient or conflicting; an analyst must review it.",
+ },
+)
+print("TRIAGE: {} (conf={:.0%})".format(triage.value, triage.confidence))
+
+# Tier 2: caller-controlled escalation to Claude when Jev is uncertain
+if triage.value == "escalate" or triage.confidence < 0.88:
deep_llm = LiteLLM(model="anthropic/claude-sonnet-5")
deep = context.query_with_reasoning(
"Full MITRE ATT&CK analysis of this alert: identify the attack chain, "
@@ -584,16 +686,24 @@ if triage["confidence"] < 0.88:
max_hops=3,
)
print("DEEP ANALYSIS: {}".format(deep["response"]))
-
- context.record_decision(
- category="escalation",
- scenario="Scheduled task T1053.005 on ws-finance-03 — Tier 1 conf {:.0%}".format(triage["confidence"]),
- reasoning=deep["reasoning_path"],
- outcome="escalated_tier2",
- confidence=deep["confidence"],
- entities=["ws-finance-03", "jsmith", "T1053.005"],
- decision_maker="soc_pipeline_v3",
- )
+ outcome = "escalated_tier2"
+ confidence = deep["confidence"]
+ reasoning = deep["reasoning_path"]
+else:
+ outcome = str(triage.value)
+ confidence = triage.confidence
+ reasoning = "Semantica evidence and runbook policy were evaluated before Jev routing."
+
+context.record_decision(
+ category="soc_triage",
+ scenario="Scheduled task T1053.005 on ws-finance-03 — Jev conf {:.0%}".format(triage.confidence),
+ reasoning=reasoning,
+ outcome=outcome,
+ confidence=confidence,
+ entities=["ws-finance-03", "jsmith", "T1053.005"],
+ decision_maker="jev:{}".format(triage.model),
+ cross_system_context={"typesafe_jev": triage.to_dict()},
+)
```
</Tab>
@@ -714,6 +824,10 @@ for src in best["sources"]:
**Not validating structured outputs.** The `generate_structured()` method returns parsed JSON (a dict, or a list for a top-level array), but LLMs can still produce malformed or incomplete structures. Validate the result against your expected schema before using it downstream — or use `generate_typed()`, which validates against a Pydantic model for you.
+**Treating a Noul probability as routing confidence.** Noul returns the probability of yes, so both `0.01` and `0.99` are highly certain while `0.5` is maximally uncertain. Use `result.probability` for the raw yes-probability and `result.confidence` for Semantica's derived routing certainty.
+
+**Using Jev when the output must explain itself.** Jev makes bounded typed decisions and does not generate reasoning text. Build the evidence and policy context in Semantica, use a reasoning LLM or human review when an explanation is required, and record both steps in provenance.
+
**Switching providers without testing prompt behavior.** Different models respond differently to the same prompt. A prompt optimized for GPT-4 may produce poor results with Llama or Claude. When switching providers, test your prompts and adjust temperature, instructions, or examples as needed.
**Overusing local HuggingFace models for tasks requiring latest knowledge.** Local models have a knowledge cutoff from their training date and cannot access current information. For tasks requiring up-to-date knowledge (recent CVEs, current regulations, latest threat intelligence), cloud providers with more recent training data may be necessary.
diff --git a/docs/reference/llms.md b/docs/reference/llms.md
index 2692c4b9..acf7d04c 100644
--- a/docs/reference/llms.md
+++ b/docs/reference/llms.md
@@ -1,22 +1,31 @@
---
title: "LLMs Module"
-description: "Unified interface for Groq, OpenAI, LiteLLM (Anthropic, Gemini, Ollama, DeepSeek, Azure, Bedrock, 100+ models), and HuggingFace."
+description: "Generative LLM providers plus TypeSafe Jev typed decisions."
icon: "microchip"
---
-**`semantica.llms`** provides a **single consistent API** across every major LLM provider:
+**`semantica.llms`** provides a consistent generation API across major LLM providers and a separate typed-decision API for TypeSafe Jev:
-- Every provider is a drop-in replacement for the `llm_provider=` parameter in extractors, reasoners, and agents
+- Generative providers are drop-in replacements for the `llm_provider=` parameter in extractors, reasoners, and agents
- `LiteLLM` routes to 100+ providers with a single class and model-string prefixes
- `HuggingFaceLLM` runs fully on-premise: no API key, no network calls
-- Structured output via `generate_with_schema()` for JSON extraction from any provider
+- Structured output via `generate_typed()` for schema-validated extraction
+- `Jev` and `AsyncJev` return Choice, Noul, or Score decisions without pretending to generate text
- Streaming, tool use, and `generate_batch()` for bulk inference
## Exported Classes
```python
-from semantica.llms import Groq, OpenAI, LiteLLM, HuggingFaceLLM
+from semantica.llms import (
+ AsyncJev,
+ Groq,
+ HuggingFaceLLM,
+ Jev,
+ JevDecisionResult,
+ LiteLLM,
+ OpenAI,
+)
```
| Class | Provider | API Key Required |
@@ -25,6 +34,8 @@ from semantica.llms import Groq, OpenAI, LiteLLM, HuggingFaceLLM
| `OpenAI` | OpenAI / any OpenAI-compatible gateway | `OPENAI_API_KEY` |
| `LiteLLM` | 100+ providers via LiteLLM routing | Depends on model |
| `HuggingFaceLLM` | Local HuggingFace Transformers | None (local) |
+| `Jev` | TypeSafe System One, synchronous | `TYPESAFE_API_KEY` |
+| `AsyncJev` | TypeSafe System One, asynchronous | `TYPESAFE_API_KEY` |
<Tip>
**Anthropic, Gemini, Ollama, DeepSeek, Azure, Bedrock, Cohere, and 90+ others** are all available via `LiteLLM` using their model-string prefix. See the [LiteLLM section](#litellm-100+-providers) below.
@@ -35,6 +46,7 @@ from semantica.llms import Groq, OpenAI, LiteLLM, HuggingFaceLLM
- **Unified `LLMProvider` interface**: swap providers with a one-line change, no application code changes
- **`LiteLLM`**: single class for 100+ providers using model-string routing
- **Local models**: `HuggingFaceLLM` runs fully on-premise, no API key
+- **Typed decisions**: `Jev` supports bounded Choice, Noul, and Score decisions with probability metadata
- **Streaming**: token-by-token output for low-latency UX
- **Custom gateways**: point `OpenAI` at any OpenAI-compatible endpoint via `base_url`
@@ -156,6 +168,28 @@ from semantica.llms import Groq, OpenAI, LiteLLM, HuggingFaceLLM
)
```
</Tab>
+ <Tab title="Jev: Typed Decisions">
+ Decision-only inference for bounded routing, classification, binary checks, and scoring. Use a generative provider when you need prose or multi-step reasoning.
+
+ | | |
+ | :-- | :-- |
+ | **Speed** | Very fast |
+ | **Output** | Choice, Noul, or Score |
+ | **Interface** | `decide()`; not `generate()` |
+ | **Best for** | Confidence-gated application decisions |
+
+ ```python
+ from semantica.llms import Jev
+
+ decider = Jev() # reads TYPESAFE_API_KEY
+ result = decider.decide(
+ state={"risk_score": 0.62},
+ question="How should this case be routed?",
+ kind="choice",
+ choices=["approve", "escalate"],
+ )
+ ```
+ </Tab>
</Tabs>
## API Key Setup
@@ -165,8 +199,9 @@ from semantica.llms import Groq, OpenAI, LiteLLM, HuggingFaceLLM
```bash
# Add to your shell profile (.bashrc, .zshrc, etc.)
export GROQ_API_KEY="your_groq_api_key_here"
-export OPENAI_API_KEY="your_openai_api_key_here"
+export OPENAI_API_KEY="your_openai_api_key_here"
export ANTHROPIC_API_KEY="your_anthropic_api_key_here"
+export TYPESAFE_API_KEY="your_typesafe_api_key_here"
# Reload your shell
source ~/.bashrc
@@ -216,6 +251,113 @@ llm = Groq(api_key="gsk_abc123...", model="llama-3.1-8b-instant")
llm = Groq(api_key=os.getenv("GROQ_API_KEY"), model="llama-3.1-8b-instant")
```
+## TypeSafe Jev
+
+`Jev` and `AsyncJev` wrap the official `typesafe-sdk` System One client. They are decision-only providers: neither class implements `generate()`, `generate_structured()`, or `generate_typed()`, and neither can be passed as the `llm_provider=` argument to a generative extractor or reasoner.
+
+<Warning>
+ Jev is experimental and early-access. The `llm-typesafe` extra currently supports the reviewed TypeSafe SDK 0.7 API on Python 3.10 or newer. Semantica's base installation remains compatible with Python 3.9 because the SDK is optional and guarded.
+</Warning>
+
+<Warning>
+ TypeSafe SDK 0.7 emits full request and response bodies through its `typesafe_sdk` logger at `DEBUG`; authorization headers are redacted, but application `state` is not. Keep that logger at `INFO` or higher when state may be sensitive, even if the root logger uses `DEBUG`.
+</Warning>
+
+```python
+import logging
+
+logging.getLogger("typesafe_sdk").setLevel(logging.INFO)
+```
+
+```bash
+pip install "semantica[llm-typesafe]"
+```
+
+### Constructors
+
+```python
+Jev(
+ model="jev-latest",
+ api_key=None,
+ client=None,
+ **client_options,
+)
+
+AsyncJev(
+ model="jev-latest",
+ api_key=None,
+ client=None,
+ **client_options,
+)
+```
+
+| Argument | Type | Description |
+| :--- | :--- | :--- |
+| `model` | `str` | TypeSafe model name or alias. Defaults to `jev-latest`. The result preserves the concrete model returned by the service. |
+| `api_key` | `Optional[str]` | API key. When omitted, the SDK reads `TYPESAFE_API_KEY`. |
+| `client` | compatible client or `None` | Optional injected `TypeSafeClient`/`AsyncTypeSafeClient`, useful for custom transports and tests. Injected clients remain caller-owned. |
+| `**client_options` | `Any` | Passed to the SDK client constructor, including `retry`, `timeout`, `headers`, `transport`, or `base_url`. |
+
+### Methods
+
+| Method | Returns | Description |
+| :--- | :--- | :--- |
+| `decide(state, question, kind, *, choices=None, criteria=None, **request_options)` | `JevDecisionResult` | Make one Choice, Noul, or Score decision. `AsyncJev.decide()` is awaited. |
+| `is_available()` | `bool` | Check locally for an injected client or both the SDK and a configured API key. It does not validate the key or make a network request. |
+| `close()` | `None` | Close a synchronous client created by `Jev`; injected clients are not closed. |
+| `aclose()` | `None` | Asynchronous equivalent for `AsyncJev`. |
+
+`state` accepts a string, mapping, or list. `question` is the instruction evaluated against that state. Inputs by kind:
+
+- `kind="choice"`: pass `choices` as a sequence of labels or a label-to-description mapping. `criteria=` is accepted as an equivalent explicit name. Do not pass both.
+- `kind="noul"`: optionally pass `criteria={"true": ..., "false": ...}`.
+- `kind="score"`: pass `criteria` as an ordered sequence of rubric levels, beginning at score zero.
+
+Additional request options are forwarded to `system_one()`, such as per-call `model`, `retry`, `timeout`, `extra_headers`, or `extra_body`.
+
+```python
+from semantica.llms import Jev
+
+jev = Jev() # TYPESAFE_API_KEY
+result = jev.decide(
+ state={"ticket": "Charged twice; please refund this today."},
+ question="Which queue should handle this ticket?",
+ kind="choice",
+ choices={
+ "billing": "Charges, invoices, or refunds",
+ "technical": "Product or integration failures",
+ "other": None,
+ },
+)
+```
+
+### `JevDecisionResult`
+
+| Field | Type | Description |
+| :--- | :--- | :--- |
+| `kind` | `Literal["choice", "noul", "score"]` | Primitive used for the decision. |
+| `value` | `Union[str, bool, float]` | Selected label, Noul boolean at the 0.5 boundary, or expected score. |
+| `probability` | `Optional[float]` | Selected-label probability for Choice, raw probability of yes for Noul, and `None` for Score. |
+| `confidence` | `float` | SDK confidence for Choice/Score; `abs(2p - 1)` routing certainty for Noul. |
+| `probabilities` | `dict` | Full Choice or Score probability distribution. Empty for Noul. |
+| `model` | `str` | Concrete model reported by TypeSafe. |
+| `request_id` | `Optional[str]` | Request ID when returned by the API. |
+| `usage` | `dict` | Reported input/output token usage. |
+| `legend` | `dict[int, Any]` | Score-level rubric; empty for Choice and Noul. |
+
+`result.to_dict()` returns a serializable copy suitable for Semantica decision metadata or `cross_system_context`. It deliberately retains the raw Noul probability separately from the derived confidence.
+
+```python
+from semantica.llms import AsyncJev
+
+async with AsyncJev() as jev:
+ result = await jev.decide(
+ state="The message asks for an immediate duplicate-charge refund.",
+ question="Does the message explicitly communicate urgency?",
+ kind="noul",
+ )
+```
+
## Providers
<CodeGroup>
@@ -285,6 +427,19 @@ llm = HuggingFaceLLM(
# Bring your own model: full local control, no API key
```
+```python TypeSafe Jev (Decision-only)
+from semantica.llms import Jev
+
+decider = Jev(model="jev-latest") # reads TYPESAFE_API_KEY
+result = decider.decide(
+ state={"risk_score": 0.62},
+ question="How should this case be routed?",
+ kind="choice",
+ choices=["approve", "escalate"],
+)
+# Best for typed, confidence-gated application decisions; no text generation
+```
+
</CodeGroup>
## LiteLLM: 100+ Providers
@@ -334,9 +489,9 @@ llm = OpenAI(
`base_url` is validated at construction time. Non-HTTP(S) schemes raise `ValueError` to prevent SSRF attacks (fixed in v0.5.0).
</Note>
-## Using in Extractors
+## Using Generative Providers in Extractors
-All extractors accept any provider as `llm_provider=`:
+Extractors accept generative providers as `llm_provider=`. Jev is not accepted here because it returns decisions rather than generated text:
```python
import os
@@ -363,6 +518,7 @@ trip = TripletExtractor(method="llm", llm_provider=llm)
| Azure OpenAI | `LiteLLM(model="azure/...")` | Fast | Medium | No | 128k | Enterprise, compliance |
| AWS Bedrock | `LiteLLM(model="bedrock/...")` | Fast | Varies | No | Varies | AWS-native workloads |
| HuggingFace | `HuggingFaceLLM` | Slow | Free | Yes | Varies | Custom models, BYOM |
+| TypeSafe Jev | `Jev` / `AsyncJev` | Very fast | Provider pricing | No | Application state | Typed routing, classification, and scoring |
<Tip>
For production extraction pipelines, Groq delivers the best throughput-to-cost ratio. For complex multi-hop reasoning, Claude Opus or GPT-4o provide the highest accuracy.
@@ -379,12 +535,13 @@ Documentation examples may showcase stronger models for better developer experie
| `Groq` | `llama-3.1-8b-instant` | Implementation default; examples use `llama-3.3-70b-versatile` for showcase |
| `OpenAI` | `gpt-3.5-turbo` | Implementation default; examples use `gpt-4o` for showcase |
| `HuggingFaceLLM` | `gpt2` | Lightweight, widely compatible |
+| `Jev` / `AsyncJev` | `jev-latest` | Early-access alias; pass a concrete model in production when reproducibility requires it |
These are the models used when you construct a provider without specifying `model=`. Examples throughout this documentation use stronger showcase models. Always pass `model=` explicitly in production for reproducible results.
**Why This Matters:**
- Reproducible extraction results across environments
-- Consistent baseline performance for benchmarking
+- Consistent baseline performance for benchmarking
- Predictable costs when scaling production workloads
## Performance and Reliability Tips
@@ -406,7 +563,7 @@ all_entities = []
for text in texts:
entities = ner.extract(text)
all_entities.extend(entities)
-
+
# Rate limiting handled automatically by provider
```
@@ -433,7 +590,7 @@ llm = Groq(
# Automatic retries for rate limits and transient errors
extractor = NERExtractor(
- method="llm",
+ method="llm",
llm_provider=llm,
max_retries=3 # Retry failed requests automatically
)
diff --git a/pyproject.toml b/pyproject.toml
index 7b0ecfde..db72f6cf 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -99,9 +99,13 @@ llm-deepseek = ["openai>=1.0.0"]
llm-novita = ["openai>=1.0.0"]
llm-litellm = ["litellm>=1.83.9"]
llm-instructor = ["instructor>=1.15.3"]
+# TypeSafe SDK has no Python 3.9 release. Jev is also early-access, so keep the
+# integration on the reviewed 0.7 response contract until compatibility with a
+# newer minor line is verified.
+llm-typesafe = ["typesafe-sdk>=0.7.0,<0.8.0; python_version >= '3.10'"]
llm-all = [
- "semantica[llm-openai,llm-groq,llm-gemini,llm-anthropic,llm-ollama,llm-deepseek,llm-novita,llm-litellm,llm-instructor]"
+ "semantica[llm-openai,llm-groq,llm-gemini,llm-anthropic,llm-ollama,llm-deepseek,llm-novita,llm-litellm,llm-instructor,llm-typesafe]"
]
# ---- Document Parsing ----
diff --git a/requirements-ci.txt b/requirements-ci.txt
index 7e93f6b2..7b5fed91 100644
--- a/requirements-ci.txt
+++ b/requirements-ci.txt
@@ -2029,6 +2029,7 @@ httpx2==2.12.0 \
# via
# anthropic
# langsmith
+ # typesafe-sdk
huggingface-hub==1.29.0 \
--hash=sha256:6ebb385a581435325cf6d5c5b233d5d4bc91175834d99fd65dae14379b36e9ad \
--hash=sha256:b00f7782afc14db4bc6572763810a635bdfbab8623d957bfb553bd18e03852cd
@@ -5079,6 +5080,7 @@ pydantic==2.13.5 \
# qdrant-client
# spacy
# thinc
+ # typesafe-sdk
# weasel
# weaviate-client
pydantic-core==2.46.5 \
@@ -5205,6 +5207,7 @@ pydantic-core==2.46.5 \
# via
# instructor
# pydantic
+ # typesafe-sdk
pydantic-settings==2.15.0 \
--hash=sha256:0ba092c291c94baceb5eff768aa0d56400a457585bc0175925a5a5510303da42 \
--hash=sha256:694b793e84f766ba76a90ebdefc01d0a9a045dab0382bee70393da93712ad117
@@ -6482,6 +6485,7 @@ tenacity==9.1.4 \
# google-genai
# instructor
# langchain-core
+ # typesafe-sdk
terminado==0.18.1 \
--hash=sha256:a4468e1b37bb318f8a86514f65814e1afc977cf29b3992a4500d9dd305dcceb0 \
--hash=sha256:de09f2c4b85de4765f7714688fff57d3e75bad1f909b589fde880460c753fd2e
@@ -6925,6 +6929,10 @@ typer==0.26.8 \
# spacy
# transformers
# weasel
+typesafe-sdk==0.7.1 \
+ --hash=sha256:495ce9d81733b4f95edcb156e95042a7ec4bfd59972a1150ffa8ce1e11f85a54 \
+ --hash=sha256:9d04eee13b5f64bbbe6f8e96cf40e3f39ca4efc934a1f4f39490cb9a43e9d2ad
+ # via semantica (pyproject.toml)
typing-extensions==4.16.0 \
--hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
--hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
@@ -6972,6 +6980,7 @@ typing-extensions==4.16.0 \
# soundfile
# starlette
# torch
+ # typesafe-sdk
# typing-inspection
typing-inspection==0.4.4 \
--hash=sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47 \
diff --git a/semantica/llms/__init__.py b/semantica/llms/__init__.py
index b31511ff..9932290b 100644
--- a/semantica/llms/__init__.py
+++ b/semantica/llms/__init__.py
@@ -5,22 +5,28 @@ This module provides clean, intuitive imports for LLM providers used in Semantic
It wraps the underlying provider functionality from semantica.semantic_extract.providers
to provide a cleaner API.
-Every provider wrapper exposes the same generation interface:
+Generative provider wrappers expose the same generation interface:
- generate(prompt, **kwargs) -> str
- generate_structured(prompt, **kwargs) -> dict | list
- generate_typed(prompt, schema, max_retries=3, **kwargs) -> BaseModel
- is_available() -> bool
+Jev is the intentional decision-only exception. It exposes:
+ - decide(state, question, kind, **kwargs) -> JevDecisionResult
+ - is_available() -> bool
+
Supported Providers:
- Groq: Groq API for fast inference
- OpenAI: OpenAI API (GPT-3.5, GPT-4, etc.)
- HuggingFaceLLM: HuggingFace Transformers for local LLM inference
- - LiteLLM: Unified interface to 100+ LLM providers (OpenAI, Anthropic, Groq, Azure, Bedrock, Vertex AI, etc.)
+ - LiteLLM: Unified interface to 100+ LLM providers
+ (OpenAI, Anthropic, Groq, Azure, Bedrock, Vertex AI, etc.)
- Anthropic: Anthropic Claude API (Claude sonnet, Opus, Haiku, etc.)
- Gemini: Google Gemini API
- Ollama: Local models served through Ollama
- DeepSeek: DeepSeek's OpenAI-compatible API
- Novita: Novita AI's OpenAI-compatible API
+ - Jev: TypeSafe System One typed decisions (Choice, Noul, and Score)
Example Usage:
>>> from semantica.llms import Groq, OpenAI, HuggingFaceLLM, LiteLLM, Anthropic
@@ -63,20 +69,30 @@ Example Usage:
>>> # Novita provider
>>> novita = Novita(model="deepseek/deepseek-v3.2", api_key="your-key")
>>> response = novita.generate("Hello, world!")
+ >>>
+ >>> # TypeSafe Jev (decision-only; no text generation methods)
+ >>> jev = Jev(api_key="your-key")
+ >>> decision = jev.decide(
+ ... state={"amount": 12500},
+ ... question="Should this transaction be approved?",
+ ... kind="choice",
+ ... choices=["approve", "escalate"],
+ ... )
Author: Semantica Contributors
License: MIT
"""
+from .anthropic import Anthropic
+from .deepseek import DeepSeek
+from .gemini import Gemini
from .groq import Groq
-from .openai import OpenAI
from .huggingface import HuggingFaceLLM
from .litellm import LiteLLM
-from .anthropic import Anthropic
-from .gemini import Gemini
-from .ollama import Ollama
-from .deepseek import DeepSeek
from .novita import Novita
+from .ollama import Ollama
+from .openai import OpenAI
+from .typesafe import AsyncJev, Jev, JevDecisionResult
__all__ = [
"Groq",
@@ -88,4 +104,7 @@ __all__ = [
"Ollama",
"DeepSeek",
"Novita",
+ "Jev",
+ "AsyncJev",
+ "JevDecisionResult",
]
diff --git a/semantica/llms/typesafe.py b/semantica/llms/typesafe.py
new file mode 100644
index 00000000..47f24e29
--- /dev/null
+++ b/semantica/llms/typesafe.py
@@ -0,0 +1,626 @@
+"""TypeSafe Jev decision provider.
+
+This module wraps TypeSafe's System One API as a decision-only provider. Jev
+does not generate free text, so :class:`Jev` and :class:`AsyncJev` deliberately
+do not expose the ``generate`` methods implemented by chat-LLM providers.
+
+The optional ``typesafe-sdk`` dependency is guarded so that
+``import semantica.llms`` keeps working when the SDK is not installed; a clear
+error is raised only when a caller attempts a Jev request without the optional
+dependency.
+"""
+
+from __future__ import annotations
+
+import os
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from typing import Any, Dict, List, Literal, Optional, Union
+
+from ..utils.exceptions import ProcessingError
+from ..utils.helpers import safe_import
+
+_typesafe_sdk, TYPESAFE_AVAILABLE = safe_import("typesafe_sdk")
+
+if TYPESAFE_AVAILABLE:
+ AsyncTypeSafeClient = _typesafe_sdk.AsyncTypeSafeClient
+ Choice = _typesafe_sdk.Choice
+ Noul = _typesafe_sdk.Noul
+ Score = _typesafe_sdk.Score
+ TypeSafeClient = _typesafe_sdk.TypeSafeClient
+else: # pragma: no cover - assignments are exercised through availability tests
+ AsyncTypeSafeClient = None
+ Choice = None
+ Noul = None
+ Score = None
+ TypeSafeClient = None
+
+
+JevDecisionKind = Literal["choice", "noul", "score"]
+JevDecisionValue = Union[str, bool, float]
+JevProbabilityKey = Union[str, int]
+
+_DEPENDENCY_ERROR = (
+ "TypeSafe Jev provider is unavailable because typesafe-sdk is not installed. "
+ 'Install it with: pip install "semantica[llm-typesafe]"'
+)
+_CREDENTIAL_ERROR = (
+ "TypeSafe Jev provider is unavailable because no API key is configured. "
+ "Set TYPESAFE_API_KEY or pass api_key."
+)
+
+
+@dataclass(frozen=True)
+class JevDecisionResult:
+ """Normalized result from a Jev decision.
+
+ Attributes:
+ kind: Decision primitive used: ``choice``, ``noul``, or ``score``.
+ value: Selected label, derived boolean, or expected numeric score.
+ probability: Selected-label probability for Choice, raw yes-probability
+ for Noul, and ``None`` for Score (an expected score has no single
+ corresponding probability).
+ confidence: Routing certainty in the range 0..1. Choice and Score use
+ the SDK-provided confidence. Noul derives certainty as
+ ``abs(2 * probability - 1)`` while preserving its raw probability.
+ probabilities: Full probability distribution returned for Choice or
+ Score. Noul returns a single yes-probability, so this is empty.
+ model: Concrete model reported by TypeSafe, which may differ from the
+ requested alias.
+ request_id: TypeSafe request identifier when supplied by the response.
+ usage: Token usage reported by TypeSafe.
+ legend: Score rubric keyed by numeric level; empty for other kinds.
+ """
+
+ kind: JevDecisionKind
+ value: JevDecisionValue
+ probability: Optional[float]
+ confidence: float
+ probabilities: Dict[JevProbabilityKey, float]
+ model: str
+ request_id: Optional[str]
+ usage: Dict[str, Any]
+ legend: Dict[int, Any]
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Return a JSON-compatible copy suitable for decision provenance."""
+
+ return {
+ "kind": self.kind,
+ "value": self.value,
+ "probability": self.probability,
+ "confidence": self.confidence,
+ "probabilities": dict(self.probabilities),
+ "model": self.model,
+ "request_id": self.request_id,
+ "usage": dict(self.usage),
+ "legend": dict(self.legend),
+ }
+
+
+class _JevBase:
+ """Configuration and response normalization shared by sync and async Jev."""
+
+ def __init__(
+ self,
+ model: str = "jev-latest",
+ api_key: Optional[str] = None,
+ client: Optional[Any] = None,
+ **client_options: Any,
+ ) -> None:
+ if not isinstance(model, str) or not model.strip():
+ raise ValueError("model must be a non-empty string")
+
+ self.model = model
+ self.api_key = api_key
+ self._client = client
+ self._client_options = dict(client_options)
+ self._owns_client = False
+
+ def is_available(self) -> bool:
+ """Return whether an injected client or configured SDK is available.
+
+ This is a local check for the SDK and API key. It does not validate the
+ credential or perform a network request.
+ """
+
+ return self._client is not None or (
+ TYPESAFE_AVAILABLE and self._has_configured_api_key()
+ )
+
+ def _has_configured_api_key(self) -> bool:
+ """Return whether the effective API key contains non-whitespace text."""
+
+ api_key = (
+ self.api_key
+ if self.api_key is not None
+ else os.environ.get("TYPESAFE_API_KEY")
+ )
+ return isinstance(api_key, str) and bool(api_key.strip())
+
+ @staticmethod
+ def _normalize_choice_criteria(
+ choices: Union[Sequence[str], Mapping[str, Any]],
+ ) -> Dict[str, Any]:
+ if isinstance(choices, Mapping):
+ criteria = dict(choices)
+ elif isinstance(choices, Sequence) and not isinstance(
+ choices, (str, bytes, bytearray)
+ ):
+ labels = list(choices)
+ if any(not isinstance(label, str) or not label.strip() for label in labels):
+ raise ValueError("choice labels must be non-empty strings")
+ if len(set(labels)) != len(labels):
+ raise ValueError("choice labels must be unique")
+ criteria = {label: None for label in labels}
+ else:
+ raise ValueError("choices must be a mapping or a sequence of strings")
+
+ if not criteria:
+ raise ValueError("choice decisions require at least one choice")
+ if any(not isinstance(label, str) or not label.strip() for label in criteria):
+ raise ValueError("choice labels must be non-empty strings")
+ return criteria
+
+ @classmethod
+ def _build_question(
+ cls,
+ question: Any,
+ kind: str,
+ choices: Optional[Union[Sequence[str], Mapping[str, Any]]],
+ criteria: Optional[Any],
+ ) -> Any:
+ normalized_kind = kind.lower() if isinstance(kind, str) else kind
+ if normalized_kind not in {"choice", "noul", "score"}:
+ raise ValueError("kind must be one of: choice, noul, score")
+
+ if normalized_kind == "choice":
+ if choices is not None and criteria is not None:
+ raise ValueError("pass either choices or criteria for Choice, not both")
+ choice_input = choices if choices is not None else criteria
+ if choice_input is None:
+ raise ValueError("choice decisions require choices or criteria")
+ choice_criteria = cls._normalize_choice_criteria(choice_input)
+ if TYPESAFE_AVAILABLE:
+ return Choice(instructions=question, criteria=choice_criteria)
+ return {
+ "type": "choice",
+ "instructions": question,
+ "criteria": choice_criteria,
+ }
+
+ if choices is not None:
+ raise ValueError("choices is only valid for Choice decisions")
+
+ if normalized_kind == "noul":
+ if criteria is not None:
+ if not isinstance(criteria, Mapping):
+ raise ValueError("Noul criteria must be a mapping")
+ unknown = set(criteria) - {"true", "false"}
+ if unknown:
+ names = ", ".join(sorted(str(name) for name in unknown))
+ raise ValueError(
+ "Noul criteria only supports 'true' and 'false'; "
+ f"received: {names}"
+ )
+ criteria = dict(criteria)
+ if TYPESAFE_AVAILABLE:
+ return Noul(instructions=question, criteria=criteria)
+ payload = {"type": "noul", "instructions": question}
+ if criteria is not None:
+ payload["criteria"] = criteria
+ return payload
+
+ if criteria is None:
+ raise ValueError("score decisions require ordered criteria")
+ if not isinstance(criteria, Sequence) or isinstance(
+ criteria, (str, bytes, bytearray)
+ ):
+ raise ValueError("Score criteria must be an ordered sequence")
+ score_criteria = list(criteria)
+ if not score_criteria:
+ raise ValueError("score decisions require at least one criterion")
+ if TYPESAFE_AVAILABLE:
+ return Score(instructions=question, criteria=score_criteria)
+ return {
+ "type": "score",
+ "instructions": question,
+ "criteria": score_criteria,
+ }
+
+ @staticmethod
+ def _read_field(value: Any, field: str, default: Any = None) -> Any:
+ if isinstance(value, Mapping):
+ return value.get(field, default)
+ return getattr(value, field, default)
+
+ @classmethod
+ def _normalize_usage(cls, usage: Any) -> Dict[str, Any]:
+ if usage is None:
+ return {}
+ if isinstance(usage, Mapping):
+ return dict(usage)
+ model_dump = getattr(usage, "model_dump", None)
+ if callable(model_dump):
+ dumped = model_dump()
+ if isinstance(dumped, Mapping):
+ return dict(dumped)
+ return {
+ field: getattr(usage, field)
+ for field in ("input_tokens", "output_tokens")
+ if hasattr(usage, field)
+ }
+
+ @staticmethod
+ def _validate_probability(value: Any, field: str) -> float:
+ try:
+ probability = float(value)
+ except (TypeError, ValueError) as exc:
+ raise ProcessingError(
+ f"TypeSafe returned a non-numeric {field}: {value!r}"
+ ) from exc
+ if not 0.0 <= probability <= 1.0:
+ raise ProcessingError(
+ f"TypeSafe returned {field} outside the range 0..1: {probability}"
+ )
+ return probability
+
+ @classmethod
+ def _normalize_response(cls, response: Any) -> JevDecisionResult:
+ answers = cls._read_field(response, "answers")
+ if not isinstance(answers, Mapping) or "decision" not in answers:
+ raise ProcessingError(
+ "TypeSafe response did not contain the expected 'decision' answer"
+ )
+
+ answer = answers["decision"]
+ kind = cls._read_field(answer, "type")
+ probabilities: Dict[JevProbabilityKey, float] = {}
+ legend: Dict[int, Any] = {}
+
+ if kind == "choice":
+ value = cls._read_field(answer, "choice")
+ if not isinstance(value, str) or not value:
+ raise ProcessingError("TypeSafe returned an invalid Choice value")
+ confidence = cls._validate_probability(
+ cls._read_field(answer, "confidence"), "Choice confidence"
+ )
+ raw_probabilities = cls._read_field(answer, "probabilities")
+ if not isinstance(raw_probabilities, Mapping):
+ raise ProcessingError(
+ "TypeSafe returned invalid Choice probabilities; "
+ "expected a mapping"
+ )
+ probabilities = {
+ str(label): cls._validate_probability(
+ raw_probability, f"Choice probability for {label!r}"
+ )
+ for label, raw_probability in raw_probabilities.items()
+ }
+ probability = probabilities.get(value, confidence)
+
+ elif kind == "noul":
+ probability = cls._validate_probability(
+ cls._read_field(answer, "noul"), "Noul probability"
+ )
+ value = probability >= 0.5
+ confidence = abs(2.0 * probability - 1.0)
+
+ elif kind == "score":
+ raw_value = cls._read_field(answer, "score")
+ try:
+ value = float(raw_value)
+ except (TypeError, ValueError) as exc:
+ raise ProcessingError(
+ f"TypeSafe returned a non-numeric Score value: {raw_value!r}"
+ ) from exc
+ confidence = cls._validate_probability(
+ cls._read_field(answer, "confidence"), "Score confidence"
+ )
+ probability = None
+ raw_probabilities = cls._read_field(answer, "probabilities")
+ if not isinstance(raw_probabilities, Mapping):
+ raise ProcessingError(
+ "TypeSafe returned invalid Score probabilities; "
+ "expected a mapping"
+ )
+ try:
+ probabilities = {
+ int(level): cls._validate_probability(
+ raw_probability, f"Score probability for level {level!r}"
+ )
+ for level, raw_probability in raw_probabilities.items()
+ }
+ except (TypeError, ValueError) as exc:
+ raise ProcessingError(
+ "TypeSafe returned a non-integer Score probability level"
+ ) from exc
+ raw_legend = cls._read_field(answer, "legend")
+ if not isinstance(raw_legend, Mapping):
+ raise ProcessingError(
+ "TypeSafe returned an invalid Score legend; expected a mapping"
+ )
+ try:
+ legend = {
+ int(level): description for level, description in raw_legend.items()
+ }
+ except (TypeError, ValueError) as exc:
+ raise ProcessingError(
+ "TypeSafe returned a non-integer Score legend level"
+ ) from exc
+
+ else:
+ raise ProcessingError(
+ f"TypeSafe returned an unsupported decision answer type: {kind!r}"
+ )
+
+ request_id: Optional[str]
+ try:
+ raw_request_id = cls._read_field(response, "request_id")
+ except Exception: # SDK property raises when the header was not returned.
+ raw_request_id = None
+ request_id = str(raw_request_id) if raw_request_id else None
+
+ raw_model = cls._read_field(response, "model")
+ if not isinstance(raw_model, str) or not raw_model:
+ raise ProcessingError("TypeSafe response did not include a model name")
+
+ return JevDecisionResult(
+ kind=kind,
+ value=value,
+ probability=probability,
+ confidence=confidence,
+ probabilities=probabilities,
+ model=raw_model,
+ request_id=request_id,
+ usage=cls._normalize_usage(cls._read_field(response, "usage")),
+ legend=legend,
+ )
+
+ @classmethod
+ def _validate_response_contract(
+ cls, result: JevDecisionResult, question: Any
+ ) -> None:
+ """Ensure a provider response stays inside the submitted decision domain."""
+
+ requested_kind = cls._read_field(question, "type")
+ if result.kind != requested_kind:
+ raise ProcessingError(
+ "TypeSafe returned a "
+ f"{result.kind!r} answer for a {requested_kind!r} request"
+ )
+
+ criteria = cls._read_field(question, "criteria")
+ if requested_kind == "choice":
+ if not isinstance(criteria, Mapping):
+ raise ProcessingError(
+ "TypeSafe Choice request did not contain valid criteria"
+ )
+ allowed_labels = set(criteria)
+ if result.value not in allowed_labels:
+ raise ProcessingError(
+ "TypeSafe returned a Choice value outside the requested criteria: "
+ f"{result.value!r}"
+ )
+ unexpected_labels = set(result.probabilities) - allowed_labels
+ if unexpected_labels:
+ labels = ", ".join(repr(label) for label in sorted(unexpected_labels))
+ raise ProcessingError(
+ "TypeSafe returned Choice probabilities outside the requested "
+ f"criteria: {labels}"
+ )
+ missing_labels = allowed_labels - set(result.probabilities)
+ if missing_labels:
+ labels = ", ".join(repr(label) for label in sorted(missing_labels))
+ raise ProcessingError(
+ "TypeSafe omitted Choice probabilities for requested criteria: "
+ f"{labels}"
+ )
+
+ elif requested_kind == "score":
+ if not isinstance(criteria, Sequence) or isinstance(
+ criteria, (str, bytes, bytearray)
+ ):
+ raise ProcessingError(
+ "TypeSafe Score request did not contain valid criteria"
+ )
+ allowed_levels = set(range(len(criteria)))
+ score_value = float(result.value)
+ if not allowed_levels or not 0.0 <= score_value <= max(allowed_levels):
+ raise ProcessingError(
+ "TypeSafe returned a Score value outside the requested criteria: "
+ f"{result.value!r}"
+ )
+ unexpected_levels = (
+ set(result.probabilities) | set(result.legend)
+ ) - allowed_levels
+ if unexpected_levels:
+ levels = ", ".join(str(level) for level in sorted(unexpected_levels))
+ raise ProcessingError(
+ "TypeSafe returned Score levels outside the requested criteria: "
+ f"{levels}"
+ )
+ missing_probability_levels = allowed_levels - set(result.probabilities)
+ if missing_probability_levels:
+ levels = ", ".join(
+ str(level) for level in sorted(missing_probability_levels)
+ )
+ raise ProcessingError(
+ "TypeSafe omitted Score probabilities for requested levels: "
+ f"{levels}"
+ )
+ missing_legend_levels = allowed_levels - set(result.legend)
+ if missing_legend_levels:
+ levels = ", ".join(
+ str(level) for level in sorted(missing_legend_levels)
+ )
+ raise ProcessingError(
+ "TypeSafe omitted Score legend entries for requested levels: "
+ f"{levels}"
+ )
+ mismatched_legend_levels = [
+ level
+ for level, expected_description in enumerate(criteria)
+ if result.legend[level] != expected_description
+ ]
+ if mismatched_legend_levels:
+ levels = ", ".join(str(level) for level in mismatched_legend_levels)
+ raise ProcessingError(
+ "TypeSafe returned Score legend entries that did not match "
+ f"the requested criteria at levels: {levels}"
+ )
+
+ def _require_available(self) -> None:
+ if self._client is not None:
+ return
+ if not TYPESAFE_AVAILABLE:
+ raise ProcessingError(_DEPENDENCY_ERROR)
+ if not self._has_configured_api_key():
+ raise ProcessingError(_CREDENTIAL_ERROR)
+
+
+class Jev(_JevBase):
+ """Synchronous TypeSafe Jev decision provider.
+
+ Args:
+ model: TypeSafe model or alias. Defaults to ``jev-latest``.
+ api_key: TypeSafe API key. The SDK reads ``TYPESAFE_API_KEY`` when
+ omitted.
+ client: Optional compatible synchronous client, primarily for testing
+ or custom transports. The caller retains ownership of injected
+ clients.
+ **client_options: Options forwarded to ``TypeSafeClient``.
+
+ Example:
+ >>> from semantica.llms import Jev
+ >>> jev = Jev(api_key="...")
+ >>> result = jev.decide(
+ ... state={"amount": 12500, "country": "US"},
+ ... question="Should this transaction be approved?",
+ ... kind="choice",
+ ... choices=["approve", "escalate"],
+ ... )
+ >>> result.value in {"approve", "escalate"}
+ True
+ """
+
+ def _get_client(self) -> Any:
+ self._require_available()
+ if self._client is None:
+ self._client = TypeSafeClient(
+ api_key=self.api_key,
+ model=self.model,
+ **self._client_options,
+ )
+ self._owns_client = True
+ return self._client
+
+ def decide(
+ self,
+ state: Union[str, Dict[str, Any], List[Any]],
+ question: Any,
+ kind: JevDecisionKind,
+ *,
+ choices: Optional[Union[Sequence[str], Mapping[str, Any]]] = None,
+ criteria: Optional[Any] = None,
+ **request_options: Any,
+ ) -> JevDecisionResult:
+ """Make one typed decision about application state.
+
+ ``choices`` is a Choice convenience parameter. A sequence is mapped
+ to ``{label: None}``; a mapping preserves per-label descriptions.
+ Noul accepts optional ``criteria={"true": ..., "false": ...}``, and
+ Score requires an ordered ``criteria`` sequence.
+ """
+
+ client = self._get_client()
+ decision_question = self._build_question(question, kind, choices, criteria)
+ response = client.system_one(
+ state=state,
+ questions={"decision": decision_question},
+ **request_options,
+ )
+ result = self._normalize_response(response)
+ self._validate_response_contract(result, decision_question)
+ return result
+
+ def close(self) -> None:
+ """Close a client created by this wrapper."""
+
+ if self._owns_client and self._client is not None:
+ close = getattr(self._client, "close", None)
+ if callable(close):
+ close()
+ self._client = None
+ self._owns_client = False
+
+ def __enter__(self) -> "Jev":
+ return self
+
+ def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
+ self.close()
+
+
+class AsyncJev(_JevBase):
+ """Asynchronous TypeSafe Jev decision provider.
+
+ Constructor arguments and result semantics match :class:`Jev`. Use
+ ``await decide(...)`` and ``async with`` when the wrapper owns the client.
+ """
+
+ def _get_client(self) -> Any:
+ self._require_available()
+ if self._client is None:
+ self._client = AsyncTypeSafeClient(
+ api_key=self.api_key,
+ model=self.model,
+ **self._client_options,
+ )
+ self._owns_client = True
+ return self._client
+
+ async def decide(
+ self,
+ state: Union[str, Dict[str, Any], List[Any]],
+ question: Any,
+ kind: JevDecisionKind,
+ *,
+ choices: Optional[Union[Sequence[str], Mapping[str, Any]]] = None,
+ criteria: Optional[Any] = None,
+ **request_options: Any,
+ ) -> JevDecisionResult:
+ """Asynchronously make one typed decision about application state."""
+
+ client = self._get_client()
+ decision_question = self._build_question(question, kind, choices, criteria)
+ response = await client.system_one(
+ state=state,
+ questions={"decision": decision_question},
+ **request_options,
+ )
+ result = self._normalize_response(response)
+ self._validate_response_contract(result, decision_question)
+ return result
+
+ async def aclose(self) -> None:
+ """Close a client created by this wrapper."""
+
+ if self._owns_client and self._client is not None:
+ close = getattr(self._client, "aclose", None)
+ if callable(close):
+ await close()
+ self._client = None
+ self._owns_client = False
+
+ async def __aenter__(self) -> "AsyncJev":
+ return self
+
+ async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
+ await self.aclose()
+
+
+__all__ = [
+ "AsyncJev",
+ "Jev",
+ "JevDecisionResult",
+]
diff --git a/tests/test_llm_typesafe.py b/tests/test_llm_typesafe.py
new file mode 100644
index 00000000..70fbab83
--- /dev/null
+++ b/tests/test_llm_typesafe.py
@@ -0,0 +1,700 @@
+"""Tests for the decision-only TypeSafe Jev provider wrappers."""
+
+import json
+import re
+from datetime import datetime
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+import toml
+
+import semantica.llms.typesafe as typesafe_module
+from semantica.context import Decision
+from semantica.context.decision_models import deserialize_decision, serialize_decision
+from semantica.llms import AsyncJev, Jev, JevDecisionResult
+from semantica.utils.exceptions import ProcessingError
+
+
+def _answer(kind, **fields):
+ return SimpleNamespace(type=kind, **fields)
+
+
+def _response(answer, request_id="req_123"):
+ return SimpleNamespace(
+ answers={"decision": answer},
+ model="jev-2026-09-15",
+ request_id=request_id,
+ usage=SimpleNamespace(input_tokens=120, output_tokens=4),
+ )
+
+
+def _question_payload(question):
+ """Return comparable data for real SDK models and dependency-free stubs."""
+
+ if isinstance(question, dict):
+ return question
+ return question.model_dump(exclude_none=True)
+
+
+def _choice_response():
+ return _response(
+ _answer(
+ "choice",
+ choice="approve",
+ confidence=0.91,
+ probabilities={"approve": 0.91, "escalate": 0.09},
+ )
+ )
+
+
+def test_exports_decision_only_public_surface():
+ client = MagicMock()
+
+ assert JevDecisionResult is typesafe_module.JevDecisionResult
+ assert not hasattr(Jev(client=client), "generate")
+ assert not hasattr(Jev(client=client), "generate_structured")
+ assert not hasattr(AsyncJev(client=client), "generate")
+
+
+def test_is_available_false_without_sdk_or_injected_client(monkeypatch):
+ monkeypatch.setattr(typesafe_module, "TYPESAFE_AVAILABLE", False)
+ jev = Jev()
+
+ assert jev.is_available() is False
+ with pytest.raises(ProcessingError, match=r"semantica\[llm-typesafe\]"):
+ jev.decide("state", "question", "noul")
+
+
+def test_is_available_requires_local_credentials(monkeypatch):
+ monkeypatch.setattr(typesafe_module, "TYPESAFE_AVAILABLE", True)
+ monkeypatch.delenv("TYPESAFE_API_KEY", raising=False)
+
+ assert Jev().is_available() is False
+ assert Jev(api_key="test-key").is_available() is True
+
+ monkeypatch.setenv("TYPESAFE_API_KEY", "environment-key")
+ assert Jev().is_available() is True
+
+
+def test_whitespace_only_credentials_are_rejected(monkeypatch):
+ monkeypatch.setattr(typesafe_module, "TYPESAFE_AVAILABLE", True)
+ monkeypatch.setenv("TYPESAFE_API_KEY", " ")
+
+ assert Jev().is_available() is False
+ assert Jev(api_key="\t").is_available() is False
+
+ with pytest.raises(ProcessingError, match="TYPESAFE_API_KEY"):
+ Jev().decide("state", "question", "noul")
+
+
+def test_missing_credentials_raise_clear_error(monkeypatch):
+ monkeypatch.setattr(typesafe_module, "TYPESAFE_AVAILABLE", True)
+ monkeypatch.delenv("TYPESAFE_API_KEY", raising=False)
+
+ with pytest.raises(ProcessingError, match="TYPESAFE_API_KEY"):
+ Jev().decide("state", "question", "noul")
+
+
+def test_injected_client_is_available_without_optional_sdk(monkeypatch):
+ monkeypatch.setattr(typesafe_module, "TYPESAFE_AVAILABLE", False)
+ client = MagicMock()
+ client.system_one.return_value = _choice_response()
+
+ result = Jev(client=client).decide(
+ "state", "Choose a route", "choice", choices=["approve", "escalate"]
+ )
+
+ assert result.value == "approve"
+ question = client.system_one.call_args.kwargs["questions"]["decision"]
+ assert question == {
+ "type": "choice",
+ "instructions": "Choose a route",
+ "criteria": {"approve": None, "escalate": None},
+ }
+
+
+def test_choice_uses_criteria_and_preserves_response_metadata():
+ client = MagicMock()
+ client.system_one.return_value = _choice_response()
+ jev = Jev(client=client)
+
+ result = jev.decide(
+ state={"amount": 12500},
+ question="Should this transaction be approved?",
+ kind="choice",
+ choices={
+ "approve": "Policy permits automatic approval",
+ "escalate": "Human review is required",
+ },
+ timeout=2.5,
+ )
+
+ call = client.system_one.call_args
+ assert call.kwargs["state"] == {"amount": 12500}
+ assert call.kwargs["timeout"] == 2.5
+ payload = _question_payload(call.kwargs["questions"]["decision"])
+ assert payload == {
+ "type": "choice",
+ "instructions": "Should this transaction be approved?",
+ "criteria": {
+ "approve": "Policy permits automatic approval",
+ "escalate": "Human review is required",
+ },
+ }
+
+ assert result == JevDecisionResult(
+ kind="choice",
+ value="approve",
+ probability=0.91,
+ confidence=0.91,
+ probabilities={"approve": 0.91, "escalate": 0.09},
+ model="jev-2026-09-15",
+ request_id="req_123",
+ usage={"input_tokens": 120, "output_tokens": 4},
+ legend={},
+ )
+ assert result.to_dict()["request_id"] == "req_123"
+
+
+ "probability, expected_value, expected_confidence",
+ [
+ (0.0, False, 1.0),
+ (0.25, False, 0.5),
+ (0.5, True, 0.0),
+ (0.9, True, 0.8),
+ (1.0, True, 1.0),
+ ],
+)
+def test_noul_preserves_yes_probability_and_derives_routing_certainty(
+ probability, expected_value, expected_confidence
+):
+ client = MagicMock()
+ client.system_one.return_value = _response(_answer("noul", noul=probability))
+
+ result = Jev(client=client).decide(
+ state="Transaction details",
+ question="Does this transaction violate policy?",
+ kind="noul",
+ criteria={"true": "A violation exists", "false": "No violation exists"},
+ )
+
+ payload = _question_payload(
+ client.system_one.call_args.kwargs["questions"]["decision"]
+ )
+ assert payload["type"] == "noul"
+ assert payload["criteria"] == {
+ "true": "A violation exists",
+ "false": "No violation exists",
+ }
+ assert result.value is expected_value
+ assert result.probability == probability
+ assert result.confidence == pytest.approx(expected_confidence)
+ assert result.probabilities == {}
+
+
+def test_score_preserves_distribution_and_legend():
+ client = MagicMock()
+ client.system_one.return_value = _response(
+ _answer(
+ "score",
+ score=1.7,
+ confidence=0.84,
+ probabilities={0: 0.05, 1: 0.20, 2: 0.75},
+ legend={0: "low", 1: "medium", 2: "high"},
+ )
+ )
+
+ result = Jev(client=client).decide(
+ "Alert details",
+ "How urgent is this alert?",
+ "score",
+ criteria=["low", "medium", "high"],
+ )
+
+ payload = _question_payload(
+ client.system_one.call_args.kwargs["questions"]["decision"]
+ )
+ assert payload == {
+ "type": "score",
+ "instructions": "How urgent is this alert?",
+ "criteria": ["low", "medium", "high"],
+ }
+ assert result.value == 1.7
+ assert result.probability is None
+ assert result.confidence == 0.84
+ assert result.probabilities == {0: 0.05, 1: 0.20, 2: 0.75}
+ assert result.legend == {0: "low", 1: "medium", 2: "high"}
+
+
+ "kwargs, message",
+ [
+ ({"kind": "unknown"}, "kind must be one of"),
+ ({"kind": "choice"}, "require choices or criteria"),
+ (
+ {"kind": "choice", "choices": ["same", "same"]},
+ "labels must be unique",
+ ),
+ ({"kind": "choice", "choices": ["valid", 3]}, "non-empty strings"),
+ ({"kind": "noul", "choices": ["yes", "no"]}, "only valid for Choice"),
+ ({"kind": "noul", "criteria": {"maybe": None}}, "only supports"),
+ ({"kind": "score"}, "require ordered criteria"),
+ ({"kind": "score", "criteria": "low, high"}, "ordered sequence"),
+ ],
+)
+def test_invalid_question_inputs_fail_before_client_call(kwargs, message):
+ client = MagicMock()
+ jev = Jev(client=client)
+
+ with pytest.raises(ValueError, match=message):
+ jev.decide("state", "question", **kwargs)
+
+ client.system_one.assert_not_called()
+
+
+def test_sdk_errors_are_not_hidden_by_the_wrapper():
+ class AuthenticationFailure(Exception):
+ pass
+
+ client = MagicMock()
+ client.system_one.side_effect = AuthenticationFailure("bad key")
+
+ with pytest.raises(AuthenticationFailure, match="bad key"):
+ Jev(client=client).decide("state", "question", "noul")
+
+
+def test_missing_request_id_is_normalized_to_none():
+ class ResponseWithoutRequestId:
+ answers = {"decision": _answer("noul", noul=0.8)}
+ model = "jev-latest"
+ usage = {"input_tokens": 5, "output_tokens": 1}
+
+ @property
+ def request_id(self):
+ raise RuntimeError("header absent")
+
+ client = MagicMock()
+ client.system_one.return_value = ResponseWithoutRequestId()
+
+ result = Jev(client=client).decide("state", "question", "noul")
+
+ assert result.request_id is None
+
+
+def test_response_kind_must_match_requested_kind():
+ client = MagicMock()
+ client.system_one.return_value = _response(_answer("noul", noul=0.99))
+
+ with pytest.raises(ProcessingError, match="answer for a 'choice' request"):
+ Jev(client=client).decide(
+ "state", "Choose a route", "choice", choices=["approve", "escalate"]
+ )
+
+
+def test_choice_response_must_stay_inside_requested_labels():
+ client = MagicMock()
+ client.system_one.return_value = _response(
+ _answer(
+ "choice",
+ choice="admin_override",
+ confidence=0.99,
+ probabilities={"admin_override": 0.99, "approve": 0.01},
+ )
+ )
+
+ with pytest.raises(ProcessingError, match="outside the requested criteria"):
+ Jev(client=client).decide(
+ "state", "Choose a route", "choice", choices=["approve", "escalate"]
+ )
+
+
[email protected]("probabilities", [None, [], "approve=1"])
+def test_choice_response_requires_probability_mapping(probabilities):
+ client = MagicMock()
+ client.system_one.return_value = _response(
+ _answer(
+ "choice",
+ choice="approve",
+ confidence=1.0,
+ probabilities=probabilities,
+ )
+ )
+
+ with pytest.raises(ProcessingError, match="invalid Choice probabilities"):
+ Jev(client=client).decide(
+ "state", "Choose a route", "choice", choices=["approve", "escalate"]
+ )
+
+
+def test_choice_response_requires_every_requested_probability():
+ client = MagicMock()
+ client.system_one.return_value = _response(
+ _answer(
+ "choice",
+ choice="approve",
+ confidence=1.0,
+ probabilities={"approve": 1.0},
+ )
+ )
+
+ with pytest.raises(ProcessingError, match="omitted Choice probabilities.*escalate"):
+ Jev(client=client).decide(
+ "state", "Choose a route", "choice", choices=["approve", "escalate"]
+ )
+
+
+ "answer, message",
+ [
+ (
+ _answer(
+ "score",
+ score=3.0,
+ confidence=0.9,
+ probabilities={0: 0.0, 1: 0.0, 2: 0.1, 3: 0.9},
+ legend={0: "low", 1: "medium", 2: "high", 3: "critical"},
+ ),
+ "Score value outside",
+ ),
+ (
+ _answer(
+ "score",
+ score=1.5,
+ confidence=0.9,
+ probabilities={0: 0.1, 1: 0.3, 2: 0.5, 7: 0.1},
+ legend={0: "low", 1: "medium", 2: "high"},
+ ),
+ "Score levels outside",
+ ),
+ ],
+)
+def test_score_response_must_stay_inside_requested_levels(answer, message):
+ client = MagicMock()
+ client.system_one.return_value = _response(answer)
+
+ with pytest.raises(ProcessingError, match=message):
+ Jev(client=client).decide(
+ "state",
+ "How urgent is this?",
+ "score",
+ criteria=["low", "medium", "high"],
+ )
+
+
+ "answer, message",
+ [
+ (
+ _answer(
+ "score",
+ score=1.5,
+ confidence=0.9,
+ probabilities=None,
+ legend={0: "low", 1: "medium", 2: "high"},
+ ),
+ "invalid Score probabilities",
+ ),
+ (
+ _answer(
+ "score",
+ score=1.5,
+ confidence=0.9,
+ probabilities={0: 0.1, 1: 0.3, 2: 0.6},
+ legend=None,
+ ),
+ "invalid Score legend",
+ ),
+ (
+ _answer(
+ "score",
+ score=1.5,
+ confidence=0.9,
+ probabilities={0: 0.1, 1: 0.9},
+ legend={0: "low", 1: "medium", 2: "high"},
+ ),
+ "omitted Score probabilities.*2",
+ ),
+ (
+ _answer(
+ "score",
+ score=1.5,
+ confidence=0.9,
+ probabilities={0: 0.1, 1: 0.3, 2: 0.6},
+ legend={0: "low", 1: "medium"},
+ ),
+ "omitted Score legend entries.*2",
+ ),
+ (
+ _answer(
+ "score",
+ score=1.5,
+ confidence=0.9,
+ probabilities={0: 0.1, 1: 0.3, 2: 0.6},
+ legend={0: "low", 1: "moderate", 2: "high"},
+ ),
+ "did not match.*1",
+ ),
+ ],
+)
+def test_score_response_requires_complete_matching_metadata(answer, message):
+ client = MagicMock()
+ client.system_one.return_value = _response(answer)
+
+ with pytest.raises(ProcessingError, match=message):
+ Jev(client=client).decide(
+ "state",
+ "How urgent is this?",
+ "score",
+ criteria=["low", "medium", "high"],
+ )
+
+
+def test_owned_sync_client_uses_sdk_model_default_and_request_override(monkeypatch):
+ client = MagicMock()
+ client.system_one.return_value = _response(_answer("noul", noul=0.9))
+ client_type = MagicMock(return_value=client)
+ monkeypatch.setattr(typesafe_module, "TYPESAFE_AVAILABLE", True)
+ monkeypatch.setattr(typesafe_module, "TypeSafeClient", client_type)
+ monkeypatch.setattr(
+ typesafe_module,
+ "Noul",
+ lambda instructions, criteria: {
+ "type": "noul",
+ "instructions": instructions,
+ "criteria": criteria,
+ },
+ )
+
+ Jev(
+ model="jev-default",
+ api_key="test-key",
+ base_url="https://example.test",
+ ).decide("state", "question", "noul", model="jev-request")
+
+ client_type.assert_called_once_with(
+ api_key="test-key",
+ model="jev-default",
+ base_url="https://example.test",
+ )
+ assert client.system_one.call_args.kwargs["model"] == "jev-request"
+
+
+async def test_async_jev_has_sync_result_parity_and_forwards_options():
+ client = SimpleNamespace(system_one=AsyncMock(return_value=_choice_response()))
+
+ result = await AsyncJev(client=client).decide(
+ state="state",
+ question="Choose a route",
+ kind="choice",
+ choices=["approve", "escalate"],
+ model="jev-preview",
+ )
+
+ assert result == Jev(client=MagicMock())._normalize_response(_choice_response())
+ call = client.system_one.call_args
+ assert call.kwargs["model"] == "jev-preview"
+ payload = _question_payload(call.kwargs["questions"]["decision"])
+ assert payload["criteria"] == {"approve": None, "escalate": None}
+
+
+async def test_owned_async_client_uses_sdk_model_default_and_request_override(
+ monkeypatch,
+):
+ client = SimpleNamespace(
+ system_one=AsyncMock(return_value=_response(_answer("noul", noul=0.9)))
+ )
+ client_type = MagicMock(return_value=client)
+ monkeypatch.setattr(typesafe_module, "TYPESAFE_AVAILABLE", True)
+ monkeypatch.setattr(typesafe_module, "AsyncTypeSafeClient", client_type)
+ monkeypatch.setattr(
+ typesafe_module,
+ "Noul",
+ lambda instructions, criteria: {
+ "type": "noul",
+ "instructions": instructions,
+ "criteria": criteria,
+ },
+ )
+
+ await AsyncJev(
+ model="jev-default",
+ api_key="test-key",
+ base_url="https://example.test",
+ ).decide("state", "question", "noul", model="jev-request")
+
+ client_type.assert_called_once_with(
+ api_key="test-key",
+ model="jev-default",
+ base_url="https://example.test",
+ )
+ assert client.system_one.call_args.kwargs["model"] == "jev-request"
+
+
+def test_result_round_trips_as_decision_provenance():
+ client = MagicMock()
+ client.system_one.return_value = _choice_response()
+ result = Jev(client=client).decide(
+ "transaction", "Approve?", "choice", choices=["approve", "escalate"]
+ )
+ decision = Decision(
+ decision_id="decision-1",
+ category="transaction_review",
+ scenario="wire_transfer_approval",
+ reasoning="Policy and evidence were evaluated by Semantica",
+ outcome=str(result.value),
+ confidence=result.confidence,
+ timestamp=datetime(2026, 9, 21, 12, 0, 0),
+ decision_maker=f"jev:{result.model}",
+ metadata={"typesafe_jev": result.to_dict()},
+ )
+
+ restored = deserialize_decision(serialize_decision(decision))
+
+ assert restored.outcome == "approve"
+ assert restored.confidence == 0.91
+ assert restored.decision_maker == "jev:jev-2026-09-15"
+ assert restored.metadata["typesafe_jev"]["request_id"] == "req_123"
+ assert restored.metadata["typesafe_jev"]["probabilities"]["approve"] == 0.91
+
+
+def test_pyproject_guards_sdk_on_python_310_and_includes_aggregate_extra():
+ pyproject = toml.load(Path(__file__).resolve().parents[1] / "pyproject.toml")
+ extras = pyproject["project"]["optional-dependencies"]
+
+ assert extras["llm-typesafe"] == [
+ "typesafe-sdk>=0.7.0,<0.8.0; python_version >= '3.10'"
+ ]
+ assert "llm-typesafe" in extras["llm-all"][0]
+
+
+def real_sdk_transport():
+ """Exercise the published SDK without making network requests."""
+ pytest.importorskip("typesafe_sdk")
+ httpx = pytest.importorskip("httpx2")
+ requests = []
+
+ def respond(request):
+ payload = json.loads(request.content)
+ requests.append(payload)
+ question = payload["questions"]["decision"]
+ kind = question["type"]
+ if kind == "choice":
+ answer = {
+ "type": kind,
+ "choice": "approve",
+ "confidence": 0.91,
+ "probabilities": {"approve": 0.91, "escalate": 0.09},
+ }
+ elif kind == "score":
+ answer = {
+ "type": kind,
+ "score": 0.8,
+ "confidence": 0.8,
+ "probabilities": {"0": 0.2, "1": 0.8},
+ "legend": {"0": "low", "1": "high"},
+ }
+ else:
+ answer = {"type": "noul", "noul": 0.9}
+ return httpx.Response(
+ 200,
+ headers={"x-typesafe-request-id": "req_transport"},
+ json={
+ "answers": {"decision": answer},
+ "model": "jev-concrete",
+ "usage": {"input_tokens": 12, "output_tokens": 2},
+ },
+ )
+
+ return httpx.MockTransport(respond), requests
+
+
+def _assert_real_sdk_result(result, kind):
+ assert result.kind == kind
+ assert result.model == "jev-concrete"
+ assert result.request_id == "req_transport"
+ assert result.usage == {"input_tokens": 12, "output_tokens": 2}
+ if kind == "choice":
+ assert result.probabilities == {"approve": 0.91, "escalate": 0.09}
+ elif kind == "score":
+ assert result.probabilities == {0: 0.2, 1: 0.8}
+ assert result.legend == {0: "low", 1: "high"}
+ else:
+ assert result.value is True
+ assert result.probability == 0.9
+
+
+ "kind, options",
+ [
+ ("choice", {"choices": ["approve", "escalate"]}),
+ ("noul", {}),
+ ("score", {"criteria": ["low", "high"]}),
+ ],
+)
+def test_real_owned_sdk_sync_dispatch_and_model_precedence(
+ real_sdk_transport, kind, options
+):
+ transport, requests = real_sdk_transport
+ with Jev(api_key="test-key", model="jev-default", transport=transport) as provider:
+ for request_options in ({}, {"model": "jev-override"}, {}):
+ result = provider.decide(
+ "state", "question", kind, **options, **request_options
+ )
+ _assert_real_sdk_result(result, kind)
+ assert [request["model"] for request in requests] == [
+ "jev-default",
+ "jev-override",
+ "jev-default",
+ ]
+ assert all(request["state"] == "state" for request in requests)
+
+
+ "kind, options",
+ [
+ ("choice", {"choices": ["approve", "escalate"]}),
+ ("noul", {}),
+ ("score", {"criteria": ["low", "high"]}),
+ ],
+)
+async def test_real_owned_sdk_async_dispatch_and_model_precedence(
+ real_sdk_transport, kind, options
+):
+ transport, requests = real_sdk_transport
+ async with AsyncJev(
+ api_key="test-key", model="jev-default", transport=transport
+ ) as provider:
+ for request_options in ({}, {"model": "jev-override"}, {}):
+ result = await provider.decide(
+ "state", "question", kind, **options, **request_options
+ )
+ _assert_real_sdk_result(result, kind)
+ assert [request["model"] for request in requests] == [
+ "jev-default",
+ "jev-override",
+ "jev-default",
+ ]
+ assert all(request["state"] == "state" for request in requests)
+
+
+def test_typesafe_ci_pin_and_hashes_match_uv_lock():
+ root = Path(__file__).resolve().parents[1]
+ lock = toml.load(root / "uv.lock")
+ package = next(p for p in lock["package"] if p["name"] == "typesafe-sdk")
+ requirements = (root / "requirements-ci.txt").read_text()
+ entry = re.search(
+ r"(?m)^typesafe-sdk==([^\n]+)\n((?: --hash=[^\n]+\n)+)", requirements
+ )
+ assert entry is not None
+ assert entry.group(1).split()[0] == package["version"]
+ expected_hashes = {package["sdist"]["hash"]} | {
+ wheel["hash"] for wheel in package["wheels"]
+ }
+ assert set(re.findall(r"sha256:[a-f0-9]+", entry.group(2))) == expected_hashes
diff --git a/uv.lock b/uv.lock
index 1730310f..794f4bc6 100644
--- a/uv.lock
+++ b/uv.lock
@@ -8259,6 +8259,7 @@ all = [
{ name = "tokenizers" },
{ name = "torch" },
{ name = "transformers" },
+ { name = "typesafe-sdk" },
{ name = "umap-learn" },
{ name = "uvicorn", extra = ["standard"] },
{ name = "watchdog" },
@@ -8396,6 +8397,7 @@ llm-all = [
{ name = "litellm" },
{ name = "ollama" },
{ name = "openai" },
+ { name = "typesafe-sdk" },
]
llm-anthropic = [
{ name = "anthropic" },
@@ -8424,6 +8426,9 @@ llm-ollama = [
llm-openai = [
{ name = "openai" },
]
+llm-typesafe = [
+ { name = "typesafe-sdk" },
+]
media = [
{ name = "librosa", version = "0.11.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
{ name = "librosa", version = "1.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
@@ -8637,7 +8642,7 @@ requires-dist = [
{ name = "seaborn", marker = "extra == 'viz'", specifier = ">=0.13.2" },
{ name = "semantica", extras = ["db-snowflake", "db-databricks", "db-salesforce", "db-redshift", "db-bigquery", "db-arrow"], marker = "extra == 'db-all'" },
{ name = "semantica", extras = ["graph-neo4j", "graph-falkordb", "graph-amazon-neptune", "graph-apache-age", "graph-embeddings"], marker = "extra == 'graph-all'" },
- { name = "semantica", extras = ["llm-openai", "llm-groq", "llm-gemini", "llm-anthropic", "llm-ollama", "llm-deepseek", "llm-novita", "llm-litellm", "llm-instructor"], marker = "extra == 'llm-all'" },
+ { name = "semantica", extras = ["llm-openai", "llm-groq", "llm-gemini", "llm-anthropic", "llm-ollama", "llm-deepseek", "llm-novita", "llm-litellm", "llm-instructor", "llm-typesafe"], marker = "extra == 'llm-all'" },
{ name = "semantica", extras = ["split-tiktoken", "split-community", "split-topic"], marker = "extra == 'split-all'" },
{ name = "semantica", extras = ["vectorstore-qdrant", "vectorstore-weaviate", "vectorstore-pinecone", "vectorstore-milvus", "vectorstore-pgvector", "vectorstore-sqlite", "vectorstore-faiss"], marker = "extra == 'vectorstore-all'" },
{ name = "semantica", extras = ["viz", "media", "infra", "cloud", "monitoring", "watch", "llm-all", "models-huggingface", "embeddings-local", "nlp-spacy", "documents", "ingest-git", "graph-embeddings", "split-all", "graph-all", "tripletstore-oxigraph", "vectorstore-all", "parse-docling", "parse-pdf", "ingest-parquet", "ingest-arrow", "shacl", "explorer", "agno", "langchain", "google-adk"], marker = "extra == 'all'" },
@@ -8656,13 +8661,14 @@ requires-dist = [
{ name = "torch", marker = "extra == 'models-huggingface'", specifier = ">=1.13.1" },
{ name = "tqdm", specifier = ">=4.68.3" },
{ name = "transformers", marker = "extra == 'models-huggingface'", specifier = ">=4.20.0" },
+ { name = "typesafe-sdk", marker = "python_full_version >= '3.10' and extra == 'llm-typesafe'", specifier = ">=0.7.0,<0.8.0" },
{ name = "umap-learn", marker = "extra == 'viz'", specifier = ">=0.5.12" },
{ name = "uvicorn", extras = ["standard"], marker = "extra == 'explorer'", specifier = ">=0.22.0" },
{ name = "watchdog", marker = "extra == 'watch'", specifier = ">=6.0.0" },
{ name = "weaviate-client", marker = "extra == 'vectorstore-weaviate'", specifier = ">=4.0.0" },
{ name = "websockets", marker = "extra == 'explorer'", specifier = ">=15.0.1" },
]
-provides-extras = ["llm-openai", "llm-groq", "llm-gemini", "llm-anthropic", "llm-ollama", "llm-deepseek", "llm-novita", "llm-litellm", "llm-instructor", "llm-all", "documents", "parse-docling", "parse-pdf", "shacl", "db-snowflake", "db-databricks", "db-arrow", "db-salesforce", "db-redshift", "db-bigquery", "ingest-looker", "ingest-parquet", "ingest-arrow", "ingest-sap", "ingest-servicenow", "ingest-airflow", "ingest-git", "db-all", "models-huggingface", "embeddings-local", "nlp-spacy", "graph-neo4j", "graph-falkordb", "graph-amazon-neptune", "graph-apache-age", "graph-embeddings", "graph-all", "tripletstore-oxigraph", "vectorstore-faiss", "vectorstore-qdrant", "vectorstore-weaviate", "vectorstore-pinecone", "vectorstore-milvus", "vectorstore-pgvector", "vectorstore-sqlite", "vectorstore-all", "infra", "cloud", "monitoring", "viz", "media", "gpu", "agno", "langchain", "google-adk", "open-ontologies", "watch", "split-tiktoken", "split-community", "split-topic", "split-all", "explorer", "explorer-lite", "all"]
+provides-extras = ["llm-openai", "llm-groq", "llm-gemini", "llm-anthropic", "llm-ollama", "llm-deepseek", "llm-novita", "llm-litellm", "llm-instructor", "llm-typesafe", "llm-all", "documents", "parse-docling", "parse-pdf", "shacl", "db-snowflake", "db-databricks", "db-arrow", "db-salesforce", "db-redshift", "db-bigquery", "ingest-looker", "ingest-parquet", "ingest-arrow", "ingest-sap", "ingest-servicenow", "ingest-airflow", "ingest-git", "db-all", "models-huggingface", "embeddings-local", "nlp-spacy", "graph-neo4j", "graph-falkordb", "graph-amazon-neptune", "graph-apache-age", "graph-embeddings", "graph-all", "tripletstore-oxigraph", "vectorstore-faiss", "vectorstore-qdrant", "vectorstore-weaviate", "vectorstore-pinecone", "vectorstore-milvus", "vectorstore-pgvector", "vectorstore-sqlite", "vectorstore-all", "infra", "cloud", "monitoring", "viz", "media", "gpu", "agno", "langchain", "google-adk", "open-ontologies", "watch", "split-tiktoken", "split-community", "split-topic", "split-all", "explorer", "explorer-lite", "all"]
[package.metadata.requires-dev]
dev = [
@@ -9788,6 +9794,22 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/80/87/b9fd69c92c6102a066e1b86a35243f53e70bd4c709f2a26d9f4fee4f4dc0/typer-0.26.8-py3-none-any.whl", hash = "sha256:3512ca79ac5c11113414b36e80281b872884477722440691c89d1112e321a49c", size = 122564, upload-time = "2026-06-26T09:22:44.72Z" },
]
+[[package]]
+name = "typesafe-sdk"
+version = "0.7.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "httpx2" },
+ { name = "pydantic" },
+ { name = "pydantic-core" },
+ { name = "tenacity" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/dc/d4/14d9a00c759c126c814f7cfc0b2a760768214cda0708a9af49577b321ee3/typesafe_sdk-0.7.1.tar.gz", hash = "sha256:495ce9d81733b4f95edcb156e95042a7ec4bfd59972a1150ffa8ce1e11f85a54", size = 23062, upload-time = "2026-09-21T15:57:53.579Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/75/72/7e57648d27e45260b04762dd2393a81604b516a282fc5efe94cdf90ab971/typesafe_sdk-0.7.1-py3-none-any.whl", hash = "sha256:9d04eee13b5f64bbbe6f8e96cf40e3f39ca4efc934a1f4f39490cb9a43e9d2ad", size = 36366, upload-time = "2026-09-21T15:57:52.314Z" },
+]
+
[[package]]
name = "typing-extensions"
version = "4.16.0"