【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")
相关推荐
工控丫丫1 分钟前
帆软看板中经常使用的公式函数及经常搭的组合
前端·javascript·数据库
jerrywus22 分钟前
我用 GPT-6.1-sol 做了台会讲解的 3D 售货机:60 罐饮料,一口没喝上
前端·agent·claude
GeW1 小时前
国产化替代进入深水区之后Linux 与数据库为什么必须走向重建
linux
这个DBA有点耶1 小时前
云数据库半夜卡顿,CPU才30%?深挖云盘IOPS突发限制与内核挂起机制
数据库·mysql·云原生
孟陬2 小时前
Foobar 技术周刊#159:当看不懂代码时,如何高效排障调试。脏页陷阱:一条只读查询,写入数 TB 数据。推测解码:大模型加速利器
前端·人工智能·后端
Zhao-Jichao2 小时前
AI Prompting for Everyone 课程笔记 - P17 图像生成 Imaging Generation
前端
Highcharts.js2 小时前
智能数据分析组件Orbit 正式发布与快速上手体验教程
前端·人工智能·信息可视化·数据分析系统·highcharts·orbit·智能可视化
无言听风雨丶3 小时前
Redis 运维实战与排错
运维·数据库·redis
螺丝钉tina3 小时前
[Playwright ][16]Playwright + TypeScript API 自动化测试实战:API测试
前端·javascript·typescript
小天源4 小时前
智叟云集系统 · 架构与职责分层
服务器·前端·数据库