Skip to content

结构化输出 ​

以json格式输出结果

Pydantic 格式 (生产环境首选) ​

python
import os

from pydantic import BaseModel, Field
from rich import print
from langchain.chat_models import init_chat_model
from dotenv import load_dotenv
from typing import List

# 加载.env配置
load_dotenv(override=True)
api_key = os.getenv("DEEPSEEK_API_KEY")
base_url = os.getenv("DEEPSEEK_BASE_URL")

llm = init_chat_model(
	model="deepseek-flash",
	model_provider="openai",
	api_key=api_key,
	base_url=base_url,
	# DeepSeek 在 thinking 模式下不支持 tool_choice=required(结构化输出会用到)
	extra_body={"thinking": {"type": "disabled"}},
)

# 定义返回数据
class Person(BaseModel):
	"""人物信息"""
	name: str = Field(description="姓名")
	age: int = Field(description="年龄")
	occupation: str = Field(description="职业")
	banji: Banji = Field(description="所在班级信息")

class Banji(BaseModel):
	"""班级信息"""
	name: str = Field(description="班级名称")

# 绑定结构化输出
# DeepSeek 不支持 OpenAI 的 response_format=json_schema,需走 function calling
llm = llm.with_structured_output(Person, method="function_calling")

resp = llm.invoke("张三是一名30岁的软件工程师")
print(resp)

class PersonList(BaseModel):
	"""人物列表"""
	persons: List[Person] = Field(description="人物列表")

person_llm = llm.with_structured_output(PersonList, method="function_calling")
resp = person_llm.invoke("张三 30岁,李四 50岁")
print(resp)

TypeDict ​

带有声明的字典。

python
from typing_extensions import Annotated,TypedDict
from rich import print
from langchain.chat_models import init_chat_model
from dotenv import load_dotenv

# 加载.env配置
load_dotenv(override=True)
api_key = os.getenv("DEEPSEEK_API_KEY")
base_url = os.getenv("DEEPSEEK_BASE_URL")

model = init_chat_model(
	model="deepseek-flash",
	model_provider="openai",
	api_key=api_key,
	base_url=base_url,
	extra_body={"thinking": {"type": "disabled"}},
)

class MovieTypedDict(TypedDict):
	"""电影的信息"""
	title: Annotated[str, "电影的名称"]
	year: Annotated[int, "电影的上映时间,四位数"]
	director: Annotated[str, "电影的导演"]
	rating: Annotated[float, "电影的评分,满分是10分,可以包含一位小数"]

type_model = model.with_structured_output(MovieTypedDict, method="function_calling")
response = type_model.invoke("给我介绍一下电影《星际穿越》")
print(response)

json (不推荐) ​

定义复杂,容易出错。

python
from rich import print
from langchain.chat_models import init_chat_model
from dotenv import load_dotenv

# 加载.env配置
load_dotenv(override=True)
api_key = os.getenv("DEEPSEEK_API_KEY")
base_url = os.getenv("DEEPSEEK_BASE_URL")

model = init_chat_model(
	model="deepseek-flash",
	model_provider="openai",
	api_key=api_key,
	base_url=base_url,
	extra_body={"thinking": {"type": "disabled"}},
)

"""
使用 JSON Schema 定义嵌套结构
"""
# 1. 定义嵌套的 JSON Schema
project_schema = {
    "title": "MovieInfo",
    "description": "包含电影标题、上映年份、导演、演员和评分的电影对象",
    "type": "object",
    "properties": {
        "title": {"type": "string", "description": "电影标题"},
        "year": {"type": "integer", "description": "上映年份"},
        "director": {"type": "string", "description": "导演"},
        "cast": {  # 定义嵌套数组
            "type": "array",
            "description": "演员列表",
            "items": {
                "type": "object",
                "properties": {
                    "name": {"type": "string", "description": "演员姓名"},
                    "role": {"type": "string", "description": "演员角色"}
                },
                "required": ["name", "role"]
            }
        },
        "rating": {"type": "number", "description": "评分(10分制)"}
    },
    "required": ["title", "year", "director", "cast", "rating"]
}
# 绑定 JSON Schema 到模型
json_model = model.with_structured_output(project_schema,method="json_schema")
response = json_model.invoke("给我介绍一下电影《星际穿越》")
print(response)