LangChain学习笔记day04
LangChain学习笔记day04
1. 结构化输出
openai模型实现方式 (未验证)
(1) 配置环境
from typing import List
from pydantic import BaseModel, Field
- typing.List:Python 类型提示(Type Hint)中的列表类型,用于声明字段应为指定类型元素组成的列表。
- pydantic:creat_agent()中参数 response_format 可接收的3种类之一
response_format: An optional configuration for structured responses.
Can be a `ToolStrategy`, `ProviderStrategy`, or a Pydantic model class.
If provided, the agent will handle structured output during the
conversation flow.
Raw schemas will be wrapped in an appropriate strategy based on model
capabilities.
- pydantic.BaseModel:Pydantic 提供的模型基类,用于定义结构化数据模式(Schema),支持数据解析、类型验证、序列化与反序列化。
- pydantic.Field:用于为模型字段添加元数据(Metadata),例如描述、默认值、取值范围等信息;在 LLM 结构化输出场景中,字段描述会作为 Schema 的一部分提供给模型,帮助模型理解该字段应填入什么内容。
(2) 编写输出结构
class Source(BaseModel):
"""Schema for a source used by the agent"""
url: str = Field(description="The URL of the source")
class AgentResponse(BaseModel):
"""Schema for agent response with answer and sources"""
answer:str = Field(description="The agent's answer to the query")
sources:List[Source] = Field(default_factory=list, description="The sources used to answer the query")
(3) 传入相关参数
agent = create_agent(
model=apiLLM,
tools=tools,
response_format=AgentResponse,
)
deepseek-r1模型实现方式
对于使用 DeepSeek API 的 OpenAI 接口,若设置 response_format ,程序会抛出
BadRequestError(
"Error code: 400 - {'error': {'message': 'Thinking mode does not support this tool_choice', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_request_error'}}"
)
经过反复尝试及查阅源码、官方文档、官方工具issues、博客等资料,注意到如下信息:
根据DeepSeek API OpenAI兼容接入:协议级迁移实战指南-CSDN博客中的描述,DeepSeek的OpenAI接口存在部分不兼容:
不兼容层(强行使用会报错或行为异常)
Embeddings 接口 : POST / v1 / embeddings 完全不支持,DeepSeek 目前未开放 embedding 模型 API
Moderation 接口 : POST / v1/ moderations 返回 404 Not Found
Fine-tuning 相关接口 : / v1 / fine_tuning / jobs 等全部不可用
非标准字段透传 :如 response_format: { "type": "json_object" } 会被忽略,DeepSeek 不做 JSON Schema 强制约束
本人目前只能实现通过设置system_prompt约束输出,或许能在日后的学习中找到更好的方法。
prompt内容
"""
Please parse the "content" and "source" and output them in JSON format.
Put weather fields inside "content".
Put the source URL inside "source".
Content should be formatted as key-value pairs.
No markdown and No explanations.
OUTPUT MUST BE ONLY JSON.
EXAMPLE JSON OUTPUT:
{
"content": {
"日期": "2026年6月24日 星期三",
"天气": "多云 / 晴朗",
"最高温度": "30°C ~ 34°C",
"最低温度": "21°C ~ 22°C",
"风力": "微风,约7-16 km/h",
"湿度": "约47%-65%",
"空气质量": "良",
"紫外线": "强",
},
"source": "https://example.com"
}
"""
输出结果
{
"content": {
"日期": "2026年6月25日 星期四",
"天气": "晴 / 多云转晴",
"最高温度": "33°C ~ 34°C",
"最低温度": "21°C",
"风力": "微风,偏北风转南风,约2-3级",
"湿度": "约41%-82%",
"空气质量": "良(AQI约84)",
"紫外线": "很强"
},
"source": "https://tianqi.so.com/weather"
}
posted on 2026-06-25 01:39 AQHuiguang 阅读(29) 评论(0) 收藏 举报
浙公网安备 33010602011771号