【ollama】自定义结构化输出

自定义字段

models.py

python 复制代码
from typing import Union, Literal
from pydantic import BaseModel, Field

class sendGroupMsg(BaseModel):
    type: Literal['send_group_msg'] = Field(description="指令类型标识,固定为 send_group_msg")
    carenum: str = Field(description="发送群消息的问题单号,单号如567")
    msg: str = Field(description="群消息的内容")
    oper: str = Field(default="发群消息",description="具体的操作名称,固定是发群消息")

class sendMsg(BaseModel):
    type: Literal['send_msg'] = Field(description="指令类型标识,固定为 send_msg")
    carenum: str = Field(description="发送消息的问题单号,例如:567")
    msg: str = Field(description="发送的消息内容。若用户未指定具体内容")
    oper: str = Field(default="发消息",description="具体的操作名称,固定是发消息")

class sendPhoneMsg(BaseModel):
    type: Literal['send_phone_msg'] = Field(description="指令类型标识,固定为 send_phone_msg")
    carenum: str = Field(description="待发送短信的问题单号,例如:567")
    oper: str = Field(default="手机短信",description="具体的操作名称,固定是手机短信")



class AllCommands(BaseModel):
    task: Union[sendGroupMsg,
    sendPhoneMsg,sendMsg] = Field(
        description="根据输入文本判断指令类型。"
    )

main.py

python 复制代码
from typing import Union, Literal
from pydantic import BaseModel, Field
import ollama
import os
from models import AllCommands 
import sys
os.environ["NO_PROXY"] = "xxxx,127.0.0.1,localhost,::1"

client = ollama.Client(host='http://xxxx:11434')

def generate_command(user_text):
    prompt = f"""请从以下文本中严格提取指令任务。
    要求:
    1. 必须严格提取原文的单号和操作名,严禁翻译或改写。
    2. 必须根据操作语义,准确判断 type 字段。
    3. 严格按照给定的 JSON Schema 格式输出。
    4. 如果文本包含"加内容"时,使用 add_first_inof。如果文本包含"加记录"、"添加记录"时,使用add_new_info
    文本内容:"{user_text}"
    """
    print(f"🔧 正在请求模型计算:...")
    response = client.chat(
        model='ds05288b:latest',
        # model='qwen3:8b',
        messages=[{'role': 'user', 'content': prompt}],
        format=AllCommands.model_json_schema(),
        options={'temperature': 0} 
    )
    print(f"🔧 模型计算完毕,即将返回结果:...")

    result = AllCommands.model_validate_json(response.message.content)
    print(result)
    return result


while True:

    print("请输入多行文本(输入完成后按 Ctrl+D/Ctrl+Z):")
    user_question = sys.stdin.read()

    final_answer = generate_command(user_question)
    print("\n✅ 最终答案:", final_answer)

    print("🧹 [系统提示] 准备迎接下一个问题。\n")
相关推荐
香芋芋圆2 小时前
AI 冲击内卷之下,普通前端如何破局?WebGIS—— 低门槛突围赛道
前端·javascript·人工智能·学习·职场发展
琥珀色糖2 小时前
Linux守护进程
linux·终端·守护进程·会话·进程组
INS_KF2 小时前
【编程笔记】成员函数中两个 const 的区别(const Data &getData() const;)
前端·javascript·笔记
上学的小垃圾2 小时前
01-数据库系统概述
数据库
宿6743 小时前
vue3-async
前端·javascript·vue.js
YXWik63 小时前
记录前端请求接口在浏览器请求响应的Preview和Response展示的一样的问题
前端
二进制漫游记3 小时前
FastAPI项目集成 Qdrant向量数据库+阿里云Embedding完整实战(工具封装+业务调用)
数据库·python·阿里云·embedding
2501_928996223 小时前
GPT-4o换DeepSeek迁移成本多少?中科热备解析API聚合平台技术账本
前端·数据库·人工智能
东风破_3 小时前
从跨域到 WebSocket:前端跨域方案、SSE 与双向实时通信详解
前端·后端
原则猫3 小时前
TS 类型工具
前端