Skip to main content

structured-llm

一个轻量的 Python 结构化输出运行时。

它直接使用 Pydantic 类型作为 schema,不需要 .baml 文件、CLI、代码生成,也不需要额外的运行时编译器。默认行为是 BAML 风格的「output format prompt + 本地 JSON 提取/轻量修复 + Pydantic 校验」,因此不依赖特定供应商是否支持 response_format

安装依赖

普通运行依赖:

uv sync --no-config --default-index https://pypi.org/simple

开发依赖安装在 dev dependency group 中,包括 pytestpytest-asyncioruffmypy

uv sync --group dev --no-config --default-index https://pypi.org/simple

如果需要新增开发工具依赖:

uv add <package> --group dev --no-config --default-index https://pypi.org/simple

使用示例

from pydantic import BaseModel, Field
from structured_llm import StructuredClient


class Receipt(BaseModel):
    merchant: str = Field(description="商户或店铺名称")
    total: float = Field(description="收据最终支付总金额")


client = StructuredClient(model="gpt-4o-mini", debug=True)
receipt = client.run("Extract the receipt: Coffee $4.50", Receipt)

print(receipt.merchant)
print(receipt.total)

默认 OpenAI-compatible provider 会从 OPENAI_API_KEYOPENAI_BASE_URL 读取配置;如果代码里显式传入 api_keybase_url,会优先使用显式参数。examples/receipt_extraction.py 会通过 python-dotenv 自动加载本地 .env

Field(description=...) 会渲染到默认 output format prompt。debug=True 会把传给 OpenAI-compatible SDK 的 request payload 和模型解析前的原始输出打印到 stderr。默认不会发送 response_format;只有显式设置 mode="native"mode="auto" 时才会尝试 provider-native structured output。

图片输入

视觉模型可与结构化输出一起使用。通过 ImageInput 显式提供远程 URL、本地图片或 Base64 Data URL;run()arun() 都支持多个图片,且同时兼容 endpoint="chat"endpoint="responses"

from structured_llm import ImageInput, StructuredClient

client = StructuredClient(model="gpt-4o-mini")
receipt = client.run(
    "提取这张收据中的商户和总金额",
    Receipt,
    images=[ImageInput.from_file("receipt.jpg", detail="high")],
)

可用的 detail"auto"(默认)、"low""high""original"。本地文件支持 PNG、JPEG、WEBP、GIF,并会在内存中转为 Data URL;远程图片请使用 ImageInput.from_url(...),已有 Data URL 请使用 ImageInput.from_data_url(...)。模型必须支持视觉输入,图片会计入输入 token。为避免日志泄露二进制图片内容,debug=True 会脱敏 Data URL 的 Base64 主体。

只解析已有的 LLM 文本输出:

raw = """
```json
{"merchant": "Coffee Shop", "total": 4.5}

"""

receipt = client.parse(raw, Receipt)


## 开发命令

运行测试:

```bash
PYTHONDONTWRITEBYTECODE=1 uv run --no-config --default-index https://pypi.org/simple --group dev python -m pytest -p no:cacheprovider

运行 Ruff:

uv run --no-config --default-index https://pypi.org/simple --group dev ruff check .

运行 mypy:

uv run --no-config --default-index https://pypi.org/simple --group dev mypy structured_llm

当前范围

  • 支持同步调用:StructuredClient.run(...)
  • 支持异步调用:StructuredClient.arun(...)
  • 支持图片输入:URL、本地图片、Base64 Data URL
  • 支持本地解析:StructuredClient.parse(...)
  • 支持 Pydantic BaseModellist[...]dict[...]LiteralEnumTypeAdapter 可处理的类型
  • 暂不支持流式 partial object、多 provider 内置适配、BAML DSL/codegen

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

structured_llm-0.2.0.tar.gz (59.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

structured_llm-0.2.0-py3-none-any.whl (11.7 kB view details)

Uploaded Python 3

File details

Details for the file structured_llm-0.2.0.tar.gz.

File metadata

  • Download URL: structured_llm-0.2.0.tar.gz
  • Upload date:
  • Size: 59.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.7 {"installer":{"name":"uv","version":"0.10.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for structured_llm-0.2.0.tar.gz
Algorithm Hash digest
SHA256 8c7761da6ff49361ba92285df2164d1637060556ebc0ccee542428b968d69226
MD5 c3ae80f68d404c8ac6f697dafac2ff6e
BLAKE2b-256 c4a723033af5b0d394458c4f47f1b8964e32e789eb583a54d893a5447cedf207

See more details on using hashes here.

File details

Details for the file structured_llm-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: structured_llm-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 11.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.7 {"installer":{"name":"uv","version":"0.10.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for structured_llm-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2316d82dacb5be3a875fb979499f6a620a0c9c272cc224d74e9b42f933c904da
MD5 a2cd29b68855db7e8a7f4345e1c6309e
BLAKE2b-256 3bc26e5de1c82827d109cc0b31318bcf4ef2a783e1cc2c639212f42e33a8fb7b

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page