开发者指南
Jev Python 与 LangChain 实战教程:Async httpx、Pydantic v2 与 LangGraph 决策节点
面向 Python AI 工程师的 Jev 完整接入教程:用 httpx + Pydantic v2 封装强类型异步客户端,将 Jev 1.14 接入 LangChain / LangGraph 路由与安全护栏节点,并实现 asyncio 高并发批量评估。

在 Python 中接入 Jev AI,只需用 httpx.AsyncClient 调用 POST https://thejevai.com/v1/systemone,配合 Pydantic v2 校验强类型的 noul、choice、score 返回值,即可直接嵌入 FastAPI 中间件或 LangGraph 条件路由节点。 无需手写脆弱的正则解析,就能在纯 Python 代码里获得毫秒级校准决策。
绝大多数 AI 工程团队都在 Python 生态中搭建 Agent、RAG 检索与离线评测(FastAPI、Pydantic、LangChain、LangGraph)。但如果把每个内部 if 分支都丢给对话大模型来判断,整个链路会变得又慢又贵且难以预测。
本教程围绕 Jev System One 决策模型,提供三套可直接复制进项目的 Python 生产代码:异步 Pydantic 客户端、LangGraph 路由与工具护栏节点,以及 asyncio.Semaphore 并发批量评测脚本。
目录
- 为什么 Python + Pydantic v2 与 Jev 是绝配
- 用 httpx + Pydantic v2 封装强类型异步客户端
- 在 LangGraph 中接入 Jev 路由与安全护栏节点
- 结合 TypeSafe LangChain 分类器模式
- 用 asyncio.Semaphore 实现高吞吐 Python 批量评估
- 写代码前先在 Playground 验证 Schema
- 常见问题
为什么 Python + Pydantic v2 与 Jev 是绝配
Pydantic 在应用边界兜底运行时类型安全,Jev 在模型层锁定离散决策空间。两者结合直接根治 Python AI 服务最常见的两大故障:LLM 输出非法 JSON 与未经校准的胡乱打分。

用 httpx + Pydantic v2 封装强类型异步客户端
先安装依赖(pip install httpx pydantic),再封装一个带强类型校验的轻量客户端:
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"]
在 FastAPI 路由或 Celery/ARQ 异步任务里调用 decide() 后,直接用 NoulAnswer / ChoiceAnswer / ScoreAnswer 校验,IDE 全程补全。
在 LangGraph 中接入 Jev 路由与安全护栏节点
在 LangGraph Agent 编排里,最推荐把 Jev 放在两个位置:入口处的模型路由节点(判断该走快模型、强推理模型还是人工接管),以及工具执行前的安全护栏节点:

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"])
# 置信度不足时保守升级至强推理路径
route = parsed.choice if parsed.confidence >= 0.75 else "reasoning"
return {"route": route, "confidence": parsed.confidence}
如果你的团队使用 Claude Code 或 Cursor,也可以同步配合 Jev MCP 接入指南 为编辑器 Agent 提供决策工具。
结合 TypeSafe LangChain 分类器模式
即使你原本就在用 TypeSafe 官方的 langchain-typesafe(TypeSafeClassifier),底层的核心思想完全一致:用 Noul/Choice/Score 声明问题契约,用概率驱动分支。而通过 Jev AI 的 /v1/systemone 调用,你还可以用同一把 Key 无缝切换 typesafe/jev-1.14、cloudflare/clef 等 40+ 决策模型做对比实验。
用 asyncio.Semaphore 实现高吞吐 Python 批量评估
做离线 RAG 评估(Jev as a Judge)或 CSV 批量打标时,推荐用 httpx.AsyncClient(http2=True) + asyncio.Semaphore + 流式 JSONL 落盘:

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")
关于 429 指数退避、去重缓存与两级降本级联,请进一步阅读 Jev 批量处理与成本优化指南。
写代码前先在 Playground 验证 Schema
本文所有问题结构都可以先在免费的 Jev AI 在线 Playground 里零门槛验证(无需 waitlist)。调准之后,登录账号 生成 JEV_API_KEY,配合 5 分钟上手指南 或完整 API 文档 即可上线。
常见问题
Python 接入 Jev 必须装很重的 SDK 吗?
不需要,30 行 httpx + Pydantic v2 封装即可直连 POST https://thejevai.com/v1/systemone,并享受 HTTP/2 连接池与完整类型提示。
该选同步 requests 还是异步 httpx?
一次性小脚本或同步 Django/Flask 接口用 requests 即可;FastAPI、LangGraph 和高并发离线评估强烈建议用 httpx.AsyncClient(http2=True)。