2026/7/23 3:54:08

【ollama】自定义结构化输出

【ollama】自定义结构化输出 自定义字段models.pyfromtypingimportUnion,LiteralfrompydanticimportBaseModel,FieldclasssendGroupMsg(BaseModel):type:Literal[send_group_msg]Field(description指令类型标识固定为 send_group_msg)carenum:strField(description发送群消息的问题单号单号如567)msg:strField(description群消息的内容)oper:strField(default发群消息,description具体的操作名称固定是发群消息)classsendMsg(BaseModel):type:Literal[send_msg]Field(description指令类型标识固定为 send_msg)carenum:strField(description发送消息的问题单号例如567)msg:strField(description发送的消息内容。若用户未指定具体内容)oper:strField(default发消息,description具体的操作名称固定是发消息)classsendPhoneMsg(BaseModel):type:Literal[send_phone_msg]Field(description指令类型标识固定为 send_phone_msg)carenum:strField(description待发送短信的问题单号例如567)oper:strField(default手机短信,description具体的操作名称固定是手机短信)classAllCommands(BaseModel):task:Union[sendGroupMsg,sendPhoneMsg,sendMsg]Field(description根据输入文本判断指令类型。)main.pyfromtypingimportUnion,LiteralfrompydanticimportBaseModel,FieldimportollamaimportosfrommodelsimportAllCommandsimportsys os.environ[NO_PROXY]xxxx,127.0.0.1,localhost,::1clientollama.Client(hosthttp://xxxx:11434)defgenerate_command(user_text):promptf请从以下文本中严格提取指令任务。 要求 1. 必须严格提取原文的单号和操作名严禁翻译或改写。 2. 必须根据操作语义准确判断 type 字段。 3. 严格按照给定的 JSON Schema 格式输出。 4. 如果文本包含“加内容”时使用 add_first_inof。如果文本包含“加记录”、“添加记录”时使用add_new_info 文本内容{user_text} print(f 正在请求模型计算:...)responseclient.chat(modelds05288b:latest,# modelqwen3:8b,messages[{role:user,content:prompt}],formatAllCommands.model_json_schema(),options{temperature:0})print(f 模型计算完毕即将返回结果:...)resultAllCommands.model_validate_json(response.message.content)print(result)returnresultwhileTrue:print(请输入多行文本输入完成后按 CtrlD/CtrlZ)user_questionsys.stdin.read()final_answergenerate_command(user_question)print(\n✅ 最终答案,final_answer)print( [系统提示] 准备迎接下一个问题。\n)