pydantic 参数校验错误,函数中使用了pydantic 进行参数校验,使用的类如下
import pydantic
from pydantic import BaseModel
from typing import List, Any, Optional
class RobotMessage(BaseModel):
code: int = pydantic.Field(200, description="HTTP status code")
msg: str = pydantic.Field("success", description="HTTP status message")
question: str = pydantic.Field(..., description="Question text")
response: str = pydantic.Field(..., description="Response text")
source_documents: List[str] = pydantic.Field(
..., description="List of source documents"
)
class Config:
schema_extra = {
"example": {
"code": 200,
"msg": "success",
"question": "工伤保险如何办理?",
"response": "根据已知信息,可以总结如下:\n\n1. 参保单位为员工缴纳工伤保险费,以保障员工在发生工伤时能够获得相应的待遇。",
"source_documents": [
"出处 [1] 广州市单位从业的特定人员参加工伤保险办事指引.docx:\n\n\t( 一) 从业单位 (组织) 按“自愿参保”原则, 为未建 立劳动关系的特定从业人员单项参加工伤保险 、缴纳工伤保 险费。",
"出处 [2] ...",
"出处 [3] ...",]
}
}
可以看出来使用FastAPI开启的接口,返回的消息类型是RobotMessage消息,但是这个类的构造的时候要小心,因为有参数校验
r1=RobotMessage(
code="200",
msg="查询成功",
question="你是谁",
response="我是小助手",
source_documents=["我是小助手"]
)
这样构造都符合要求,所以这样构造没有错误
r2=RobotMessage(
code="500",
msg="查询失败",
question="你是谁",
response="",
source_documents=[[]]
)
但是如r2构造就会报错, File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for RobotMessage
source_documents -> 0
str type expected (type=type_error.str)
上面的意思RobotMessage类的参数source_documents的0元素期待str类型的元素,但实际元素为列表元素[],即第一个元素的类型不是str,而是列表,所以报错,将最后一行参数改为source_documents=[]就没有问题了