第11章 架构解析
架构概览
本页阐述核心执行流程及扩展或调试的切入点,重点展示最小化的同步/异步代码路径,以及流式、部分(partial)和并行模式如何融入其中。
高层流程
sequenceDiagram
autonumber
participant U as User Code
participant I as Instructor (patched)
participant R as Retry Layer (tenacity)
participant C as Provider Client
participant D as Dispatcher (process_response)
participant H as Provider Handler (response/reask)
participant M as Pydantic Model
U->>I: chat.completions.create(response_model=..., **kwargs)
Note right of I: patch() 包裹 create(),加入缓存/模板处理和重试逻辑
I->>R: retry_sync/async(func=create, max_retries, strict, mode, hooks)
loop 尝试次数
R->>C: create(**prepared_kwargs)
C-->>R: 原始响应(依提供商而定)
R->>D: process_response(_async)(response, response_model, mode, stream)
alt 流式/部分模式
D->>M: Iterable/Partial.from_streaming_response(_async)
D-->>R: Iterable/Partial 模型(或元素列表)
else 标准模式
D->>H: 提供商模式处理器(选择格式化/解析策略)
H-->>D: 如需调整,返回新的 response_model 或 kwargs
D->>M: response_model.from_response(...)
M-->>D: 解析后的模型(附带 _raw_response)
D-->>R: 模型(或适配后的简单类型)
end
R-->>I: 解析后的模型
end
I-->>U: 最终模型(实例上附带 _raw_response)
rect rgb(255,240,240)
Note over R,H: 遇校验/JSON 错误 → 触发 reask 路径
R->>H: handle_reask_kwargs(..., exception, failed_attempts)
H-->>R: 供下次尝试使用的新的 kwargs/messages
end
关键职责说明:
patch():包裹提供商的 create 方法,实现缓存查询/保存、模板处理、严格模式、钩子及重试。
重试层:执行提供商调用,触发钩子,更新用量统计,通过 reask 处理校验/JSON 错误并重试。
调度器:依据 Mode 选取正确的解析路径,处理多模态消息转换,并在返回的模型上附加 _raw_response。
提供商处理器:针对特定提供商/模式进行请求塑形及 reask 准备。
最小代码路径
同步
import openai
import instructor
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
client = instructor.from_provider("openai/gpt-5-nano")
model = client.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "{'name': 'Ada', 'age': 37}"}],
response_model=User, # 触发 schema/工具连线与解析
max_retries=3, # 基于 tenacity 的校验重试
strict=True, # 若支持则启用严格 JSON 解析
)
# 如需访问提供商原始响应
raw = model._raw_response
异步
import asyncio
import openai
import instructor
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
async def main():
aclient = instructor.from_provider("openai/gpt-5-nano", async_client=True)
model = await aclient.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "{\"name\": \"Ada\", \"age\": 37}"}],
response_model=User,
max_retries=3,
strict=True,
)
print(model)
asyncio.run(main())
流式、部分与并行
流式可迭代对象
通过 Instructor.create_iterable 调用 create_iterable(response_model=Model, stream=True 默认开启)。返回解析元素的生成器(同步)或异步生成器(异步)。内部设置 stream=True,并由 IterableBase.from_streaming_response(_async) 组装元素。
for item in client.create_iterable(messages=..., response_model=MyModel):
print(item)
部分对象
使用 create_partial(response_model=Model) 在流式过程中接收逐步填充的部分模型。内部将模型包裹为 Partial[Model] 并设置 stream=True。
for partial in client.create_partial(messages=..., response_model=MyModel):
# partial 包含已到达的字段
pass
并行工具
当一次请求需要多个工具调用时,使用 Mode.PARALLEL_TOOLS 及并行类型提示(如模型列表)。并行工具模式不支持流式。
from instructor.mode import Mode
result = client.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Extract person and event info."}],
response_model=[PersonInfo, EventInfo],
mode=Mode.PARALLEL_TOOLS,
)
钩子与重试
可用钩子观察并度流程。典型事件包括:
completion:kwargs:提供商调用前
completion:response:提供商调用后
parse:error:发生校验/JSON 错误时
completion:last_attempt:重试序列即将停止时
completion:error:来自 instructor.core 的非校验类完成错误
from instructor.core.hooks import HookName
client.on(HookName.COMPLETION_KWARGS, lambda **kw: print("KWARGS", kw))
client.on(HookName.PARSE_ERROR, lambda e: print("PARSE", e))
多模态转换位置
对需要的模式,消息通过 processing.multimodal.convert_messages 转换。特定处理器/模式可启用图像/音频/PDF 自动检测,将字符串/路径/URL 或 data URI 转换为提供商就绪的负载。
错误处理概览
校验或 JSON 解码错误会触发 reask 路径。Reask 处理器(handle_reask_kwargs)追加或调整消息以携带错误反馈,使下一次尝试得以自我纠正。若所有重试均失败,将抛出 InstructorRetryException,其中包含 failed_attempts、最后一次完成结果、用量总计及用于复现的 create kwargs。
扩展性说明
新提供商需添加用于响应与 reask 处理的 utils,并注册调度器所用的模式。多数 JSON/工具模式为共享,尽可能复用现有处理器。将提供商特定逻辑保留在提供商 utils 中,避免使中央调度器超出路由与编排范畴。