Back to all articles

Developer Guides

Jev Python & LangChain Guide: Async httpx, Pydantic v2 & LangGraph Decision Nodes

Complete Python developer tutorial for Jev AI: build a typed async httpx + Pydantic v2 client, wire Jev 1.14 into LangChain and LangGraph routing/guardrail nodes, and run asyncio batch evals.

By Jev AINov 30, 20263 min read
Jev Python & LangChain Guide: Async httpx, Pydantic v2 & LangGraph Decision Nodes

To use Jev AI in Python, call POST https://thejevai.com/v1/systemone with httpx.AsyncClient, validate the typed noul, choice, and score answers with Pydantic v2, and drop the client directly into FastAPI middleware or LangGraph conditional routing nodes. You get sub-second calibrated decisions in pure Python with full static typing and zero brittle regex parsing.

Most AI engineering teams build their agents, RAG pipelines, and offline evaluation suites in Python—using FastAPI, Pydantic, LangChain, or LangGraph. Yet relying on a chat LLM for every internal if branch makes Python agent loops slow, unpredictable, and expensive.

This tutorial gives you production-ready Python patterns for the Jev System One model: a reusable async Pydantic client, a LangGraph routing and pre-tool guardrail harness, and an asyncio.Semaphore batch evaluator.

Table of contents

Why pair Jev with Python & Pydantic v2

Pydantic enforces strict runtime types at your application boundary, while Jev enforces strict decision boundaries at the model layer. Putting them together eliminates the two most common failure modes in Python AI services: malformed JSON outputs and uncalibrated LLM guesses.

Type-safe Python pipeline diagram: Pydantic State Payload, Async httpx Client, Pydantic v2 Answer Parsing, and Safe Application Branching

Typed async Python client with httpx and Pydantic v2

Install httpx and pydantic (pip install httpx pydantic) and create a clean client module that validates every Jev response:

import os
from typing import Any, Literal
import httpx
from pydantic import BaseModel, Field


class NoulAnswer(BaseModel):
    type: Literal["noul"]
    noul: float = Field(ge=0.0, le=1.0)


class ChoiceAnswer(BaseModel):
    type: Literal["choice"]
    choice: str
    probabilities: dict[str, float]
    confidence: float = Field(ge=0.0, le=1.0)


class ScoreAnswer(BaseModel):
    type: Literal["score"]
    score: float
    legend: dict[str, str]
    probabilities: dict[str, float]
    confidence: float = Field(ge=0.0, le=1.0)


class JevClient:
    def __init__(self, api_key: str | None = None, model: str = "typesafe/jev-1.14"):
        self.api_key = api_key or os.environ["JEV_API_KEY"]
        self.model = model
        self.url = "https://thejevai.com/v1/systemone"

    async def decide(
        self,
        client: httpx.AsyncClient,
        state: str | dict[str, Any] | list[str],
        questions: dict[str, Any],
        model: str | None = None,
    ) -> dict[str, Any]:
        res = await client.post(
            self.url,
            headers={
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json",
            },
            json={
                "model": model or self.model,
                "state": state,
                "questions": questions,
            },
            timeout=15.0,
        )
        res.raise_for_status()
        return res.json()["data"]["result"]["answers"]

Calling decide() inside a FastAPI endpoint or background worker lets you validate each answer key into NoulAnswer, ChoiceAnswer, or ScoreAnswer with full IDE autocomplete.

Adding a Jev decision & guardrail node to LangGraph

In a LangGraph agent, insert Jev in two places: a router node at entry (deciding whether a prompt needs a fast model, a deep reasoning model, or immediate human handoff) and a pre-tool guardrail node right before side-effecting tool execution:

LangGraph agent architecture diagram with Jev Router Node branching to Fast LLM, Reasoning LLM, or Human Interrupt, followed by a Jev Pre-Tool Safety Gate

import httpx
from typing import Literal, TypedDict


class AgentState(TypedDict):
    user_prompt: str
    route: Literal["fast", "reasoning", "human"]
    confidence: float


async def jev_router_node(state: AgentState) -> dict:
    jev = JevClient()
    async with httpx.AsyncClient(http2=True) as client:
        answers = await jev.decide(
            client,
            state=state["user_prompt"],
            questions={
                "tier": {
                    "type": "choice",
                    "instructions": "Select the safest and most cost-effective handler for this prompt.",
                    "criteria": {
                        "fast": "Simple lookup, formatting, or single-step extraction",
                        "reasoning": "Complex debugging, architecture, or multi-step synthesis",
                        "human": "Account security, legal dispute, or billing refund request",
                    },
                }
            },
        )
    parsed = ChoiceAnswer.model_validate(answers["tier"])
    # Fall back to reasoning or human when confidence is low
    route = parsed.choice if parsed.confidence >= 0.75 else "reasoning"
    return {"route": route, "confidence": parsed.confidence}

Because routing takes a fraction of a second, your LangGraph app avoids wasting expensive reasoning tokens on simple requests while keeping uncertain cases safely escalated. For coding-agent tool protocols, see our dedicated Jev MCP Server guide as well.

Using TypeSafe’s LangChain classifier pattern

If you already use TypeSafe’s official LangChain integration (langchain-typesafe), the exact same mental model applies: construct Noul, Choice, or Score objects inside TypeSafeClassifier, invoke them over your state dictionary, and branch on response.nouls["urgent"].noul. Calling Jev AI’s hosted /v1/systemone endpoint via JevClient gives you the additional benefit of swapping seamlessly between typesafe/jev-1.14, cloudflare/clef, and 40+ other decision models using one key and one credit balance.

High-throughput Python batch evaluation with asyncio

For offline RAG grading (Jev as a Judge) or CSV classification, pair httpx.AsyncClient(http2=True) with asyncio.Semaphore and streaming JSONL output:

Python asyncio Semaphore batch evaluation diagram with HTTP/2 connection pooling and crash-safe JSONL output

import asyncio, json, httpx


async def run_python_batch(rows: list[dict], out_path: str, concurrency: int = 8):
    jev = JevClient()
    sem = asyncio.Semaphore(concurrency)

    async def eval_one(client: httpx.AsyncClient, row: dict):
        async with sem:
            answers = await jev.decide(
                client,
                state=row["text"],
                questions={
                    "grounded": {"type": "noul", "instructions": "Supported by context?"},
                },
            )
            return {"id": row["id"], "answers": answers}

    async with httpx.AsyncClient(http2=True) as client:
        tasks = [eval_one(client, r) for r in rows]
        with open(out_path, "a", encoding="utf-8") as f:
            for coro in asyncio.as_completed(tasks):
                f.write(json.dumps(await coro, ensure_ascii=False) + "\n")

For retry backoff, deduplication, and tiered cost routing across 100k+ records, check out our Jev Batch Processing & Cost Guide.

Testing your schema before writing Python

Every question schema in this tutorial can be prototyped live in the free Jev AI Playground with no waitlist. Once the probabilities look right on 10–20 real examples, sign in to create your JEV_API_KEY and follow our 5-minute How to Use Jev AI guide or full API Docs.

Frequently asked questions

Do I need a heavy SDK to call Jev from Python?

No. A 30-line httpx + Pydantic v2 wrapper around POST https://thejevai.com/v1/systemone gives you async HTTP/2 pooling, strict runtime typing, and instant access to every decision model on Jev AI.

Should I use sync requests or async httpx?

Use requests for quick scripts or synchronous Django/Flask views; use httpx.AsyncClient(http2=True) for FastAPI, LangGraph, and asyncio batch pipelines where parallel throughput matters.

Can my Python code switch between Jev 1.14 and Cloudflare Clef without code changes?

Yes—pass model="cloudflare/clef-flash" or model="typesafe/jev-1.14" to jev.decide() while keeping your Pydantic response models identical.

© 2026 Jev AI JournalBack home