十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

CAMEL schemas 结构化输出转换器实战指南:从 OpenAI 到 Outlines 的 Schema 转换全解析

CAMEL schemas 结构化输出转换器实战指南:从 OpenAI 到 Outlines 的 Schema 转换全解析 CAMEL schemas 结构化输出转换器实战指南从 OpenAI 到 Outlines 的 Schema 转换全解析【免费下载链接】camel CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org项目地址: https://gitcode.com/GitHub_Trending/ca/camel结构化输出Structured Output是构建可靠 Agent 应用的关键能力。CAMEL 框架在camel/schemas模块中提供了统一、可插拔的 Schema 转换器Schema Converter体系无论是闭源的 OpenAI 模型还是通过 Outlines 约束解码的本地开源模型都能把大模型的自由文本稳定转换为符合 Pydantic 模型、JSON Schema 或正则约束的结构化结果。本文以 docs/camel.schemas.rst 对应的模块为骨架结合源码、示例与测试完整讲解BaseConverter、OpenAISchemaConverter与OutlinesConverter的设计、参数、底层原理与实战用法读完即可在自己的 Agent 流程中落地可靠的 Schema 化输出。模块总览schemas 在 CAMEL 中的定位camel/schemas是 CAMEL 的响应格式管理层它把让模型输出符合指定 Schema这一能力抽象成可替换的转换器对象。从源码看该包的对外导出非常精简camel/schemas/init.pyfrom .openai_converter import OpenAISchemaConverter from .outlines_converter import OutlinesConverter __all__ [OpenAISchemaConverter, OutlinesConverter]包内共有 4 个文件对应 RST 文档列出的子模块结构子模块文件路径核心类职责camel.schemas.basecamel/schemas/base.pyBaseConverter定义转换器的抽象接口camel.schemas.openai_convertercamel/schemas/openai_converter.pyOpenAISchemaConverter基于 OpenAI 模型的原生结构化输出camel.schemas.outlines_convertercamel/schemas/outlines_converter.pyOutlinesConverter基于 Outlines 库的约束解码转换camel.schemas模块内容camel/schemas/init.py—统一导出与命名空间该模块是整个框架结构化响应能力的底层基础设施上层的ChatAgent在调用step(..., response_format...)时即依赖这类转换机制test/schema_outputs与examples/structured_response中的用例都直接或间接建立在它之上。因此理解 schemas 模块就等于理解了 CAMEL 中如何让模型输出严格符合 Schema的完整链路。BaseConverter所有转换器的统一抽象BaseConverter定义在 camel/schemas/base.py它继承abc.ABC是整个模块的协议契约。其核心职责是管理响应格式response format并声明唯一一个抽象方法class BaseConverter(ABC): abstractmethod def convert(self, content: str, *args: Any, **kwargs: Dict[str, Any]) - Any: Structures the input text into the expected response format.接口要点入参content是待结构化的原始文本*args/**kwargs用于传递output_schema期望的响应格式通常是 PydanticBaseModel类型以及可选的自定义prompt返回Any即转换后的结构化结果具体类型由实现类决定可能是BaseModel实例、dict或普通str。从设计上看BaseConverter只约定输入文本 输出 Schema → 结构化结果这一最小语义把用什么模型、用什么解码策略完全交给子类实现。这为上层提供了一致的调用入口同时允许在 OpenAI 结构化输出与本地约束解码之间自由切换。OpenAISchemaConverter基于 OpenAI 模型的原生结构化输出OpenAISchemaConvertercamel/schemas/openai_converter.py是把字符串或函数转换为BaseModelSchema 的实现适用于通过 OpenAI 平台或兼容平台获得可靠 JSON 结构化输出的场景。构造参数类构造器签名如下源码 L61-L75def __init__( self, model_type: ModelType ModelType.GPT_4O_MINI, model_config_dict: Optional[Dict[str, Any]] None, api_key: Optional[str] None, ):参数类型默认值说明model_typeModelTypeModelType.GPT_4O_MINI使用的模型类型来自 camel/types/enums.py 的枚举model_config_dictOptional[Dict]None会透传给openai.ChatCompletion.create()的附加配置字典如temperature、max_tokens等为None时内部使用空字典api_keyOptional[str]NoneOpenAI API Key为None时自动从环境变量OPENAI_API_KEY读取值得注意的底层实现细节API Key 强制校验构造器上装饰了api_keys_required([(api_key, OPENAI_API_KEY)])源码 L56-L60即既允许显式传api_key也允许设置环境变量OPENAI_API_KEY两者都没有时会在初始化阶段报错拦截避免运行时才发现凭据缺失客户端复用框架工厂内部通过ModelFactory.create(ModelPlatformType.OPENAI, model_type, api_keyapi_key)._client源码 L70-L74构建 OpenAI 客户端而不是自己 new 一个裸客户端——这意味着它与 CAMEL 的 ModelFactory 模型管理体系完全打通默认转换 Prompt模块级常量DEFAULT_CONVERTER_PROMPTS源码 L30-L33定义了默认系统提示词从用户文本中提取关键实体与属性并转换为结构化 JSON 格式用于引导模型聚焦于结构化抽取。convert 方法与三种 Schema 输入形态核心方法convert(content, output_schema, prompt)定义在 源码 L77-L120def convert( self, content: str, output_schema: Union[Type[BaseModel], str, Callable], prompt: Optional[str] DEFAULT_CONVERTER_PROMPTS, ) - BaseModel:output_schema支持三种形态统一由 camel/utils/response_format.py 的get_pydantic_model归一化为 Pydantic 模型类输入形态说明处理逻辑Type[BaseModel]直接传入 Pydantic 模型类校验必须是BaseModel子类否则抛出ValueErrorstrJSON 编码的字符串模板用json.loads解析为字典再通过 Pydantic 的create_model动态创建TemporaryModelCallable一个普通函数将其参数签名转换为BaseModel函数装饰器语义函数即 Schema 描述转换流程中还有两处显式的防御性校验若output_schema为None直接抛出ValueError(Expected an output schema, got None.)源码 L94-L95若传入的不是BaseModel子类抛出ValueError(fExpected a BaseModel, got {type(output_schema)})源码 L98-L101。底层原理Structured Outputs 解析OpenAISchemaConverter并未使用传统的 JSON 模式而是直接调用 OpenAI 的Structured Outputs接口源码 L103-L111self.model_config_dict[response_format] output_schema response self._client.beta.chat.completions.parse( messages[ {role: system, content: prompt}, {role: user, content: content}, ], modelself.model_type, **self.model_config_dict, )关键点把output_schema直接写入response_format交给服务端做 Schema 约束使用beta.chat.completions.parse端点返回结果带.parsed字段即已解析为 Pydantic 对象的响应返回前还有一次类型兜底校验源码 L115-L118若message.parsed不是预期的output_schema类型则报错保证返回对象的类型安全。三种 Schema 输入的测试验证仓库测试 test/schema_outputs/test_openai_converter.py 用同一个天气信息抽取场景完整验证了三种输入形态等价可用test_openai_converter_with_str_templateL30-L46传入 JSON 字符串模板{location: Beijing, date: 2023-09-01, temperature: 30.0}对 Today is 2023-09-01, the temperature in Beijing is 30 degrees. 抽取结果断言为{location: Beijing, date: 2023-09-01, temperature: 30.0}test_openai_converter_with_functionL49-L61传入get_temperature(location, date, temperature)函数函数签名即 Schematest_openai_converter_with_modelL64-L76传入TemperaturePydantic 模型类字段为location: str、date: str、temperature: float。测试断言统一使用structured_output.model_dump()比较字典说明无论以何种形态定义 Schema转换结果最终都以标准 Pydantic 模型对象返回接口行为完全一致。OutlinesConverter基于 Outlines 的本地约束解码转换OutlinesConvertercamel/schemas/outlines_converter.py面向另一类场景不依赖云端结构化输出 API而是在本地通过 Outlines 库对模型生成过程施加硬约束正则、JSON Schema、类型、枚举、文法从解码层面保证输出合法。构造参数与平台支持def __init__( self, model_type: str, platform: Literal[ vllm, transformers, mamba, llamacpp, mlx ] transformers, **kwargs: Any, ):参数说明model_type本地模型的名称/标识例如 HuggingFace 模型名或本地模型路径platform模型加载平台默认transformers可选值有vllm、transformers、mamba、llamacpp、mlx**kwargs透传给 Outlinesmodels模块的额外参数平台分发的实现源码 L51-L65使用 Python 3.10 的match语句vllm对应models.vllm(...)transformers对应models.transformers(...)mamba对应models.mamba(...)llamacpp对应models.llamacpp(...)mlx对应models.mlxlm(...)其余值抛出ValueError(fUnsupported platform: {platform})。Outlines 的模型对象在构造阶段创建后续所有转换方法复用它。六类约束转换方法OutlinesConverter没有把能力塞进一个convert而是拆分为 6 个语义明确的专用方法每种对应 Outlines 的一种约束解码策略方法对应 Outlines API用途返回类型convert_regex(content, regex_pattern)outlines.generate.regex输出匹配指定正则strconvert_json(content, output_schema)outlines.generate.json按 JSON Schema字符串或可调用对象输出dictconvert_pydantic(content, output_schema)outlines.generate.json按 Pydantic 模型约束输出BaseModelconvert_type(content, type_name)outlines.generate.format输出为指定类型int/float/bool/datetime.date等strconvert_choice(content, choices)outlines.generate.choice输出必须是给定候选列表之一strconvert_grammar(content, grammar)outlines.generate.cfg按上下文无关文法CFG约束输出str其中convert_type支持的类型源码 L129-L153包括int、float、bool、datetime.date、datetime.time、datetime.datetime以及 Outlines 文档中列出的自定义类型。统一入口 convert除各专用方法外convert源码 L189-L249提供了按名称分发的统一入口def convert(self, content: str, type: Literal[regex, json, type, choice, grammar], **kwargs) - Any:type参数取值为regex/pydantic/json/type/choice/grammar对应分发到上表六个方法**kwargs中按类型传入对应参数如regex_pattern、output_schema、type_name、choices、grammar。不支持的取值抛出ValueError(Unsupported output schema type)。两种 Converter 的对比小结维度OpenAISchemaConverterOutlinesConverter依赖模型平台OpenAI云端 API本地模型transformers/vllm/mamba/llamacpp/mlx约束方式服务端 Structured Outputsparse端点本地解码期约束Outlines 库Schema 输入Pydantic 类 / JSON 字符串 / 函数Pydantic 类 / JSON Schema / 正则 / 类型 / 枚举 / 文法返回类型BaseModelstr/dict/BaseModel视方法而定典型场景追求易用性与云端能力本地部署、数据不出域、强解码约束实战在 ChatAgent 中让响应严格符合 Schema虽然schemas模块本身只负责转换但它在实际项目中最常见的用法是配合ChatAgent的response_format参数使用。仓库示例 examples/structured_response/json_format_response.py 展示了最小可用闭环from pydantic import BaseModel, Field from camel.agents import ChatAgent from camel.models import ModelFactory from camel.types import ModelPlatformType, ModelType assistant_sys_msg You are a helpful assistant. model ModelFactory.create( model_platformModelPlatformType.DEFAULT, model_typeModelType.DEFAULT, ) camel_agent ChatAgent(assistant_sys_msg, modelmodel) # pydantic basemodel as input params format class JokeResponse(BaseModel): joke: str Field(descriptiona joke) funny_level: str Field(descriptionFunny level, from 1 to 10) response camel_agent.step(Tell me a joke., response_formatJokeResponse) print(response.msgs[0].content) # {joke: Why couldnt the bicycle find its way home? It lost its bearings!, funny_level: 8}实战要点用 Pydantic 定义 SchemaField(description...)中的描述会作为模型的提示信息帮助模型理解每个字段的语义建议始终填写直接传入模型类step(..., response_formatJokeResponse)返回的response.msgs[0].content即为可安全解析的结构化 JSON 字符串与工具调用结合示例 examples/structured_response/json_format_reponse_with_tools.py 展示了给ChatAgent挂载MathToolkit、SearchToolkit等工具的同时使用response_formatSchema让 Agent 在完成估算牛津大学校龄并加 10 年这类需要推理检索的任务后输出仍能严格落在{current_age: ..., calculated_age: ...}的 Schema 里Prompt 工程辅助同目录的 examples/structured_response/structure_response_prompt_engineering.py 说明在复杂任务中还可以通过精心设计系统提示词进一步稳定输出格式。使用建议与限制优先使用 OpenAISchemaConverter当你的模型来自 OpenAI 平台且网络环境允许时它是成本最低、体验最顺滑的方案——只需要定义 Pydantic 模型其余交给服务端本地部署选择 OutlinesConverter当数据敏感、需要本地推理时OutlinesConverter的约束解码从机制上保证了格式合法非法输出在解码期就不可能产生但它要求正确安装 Outlines 及对应平台依赖transformers/vllm 等并需结合本仓库 pyproject.toml 中的依赖声明确认环境两类转换器都要求类型安全OpenAISchemaConverter在解析后校验parsed类型OutlinesConverter在平台与type取值上做显式校验错误会在调用点尽早暴露API Key 前置条件使用OpenAISchemaConverter前务必配置OPENAI_API_KEY环境变量或显式传入api_key否则初始化即失败。总结camel/schemas是 CAMEL 结构化输出能力的统一抽象层BaseConverter定义了文本 → 结构的契约OpenAISchemaConverter借助 OpenAI Structured Outputs 为云端模型提供开箱即用的 Pydantic 解析OutlinesConverter借助约束解码为本地模型提供正则、JSON、类型、枚举、文法六种细粒度约束。二者通过ChatAgent.response_format与上层 Agent 流程无缝衔接并得到 test/schema_outputs/test_openai_converter.py 与 examples/structured_response 的完整验证。在构建需要可靠结构化输出的多智能体应用时根据模型部署形态在两种转换器之间选择即可让 Agent 的输出始终有章可循。【免费下载链接】camel CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org项目地址: https://gitcode.com/GitHub_Trending/ca/camel创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表