返回顶部
热门问答 更多热门问答
技术文章 更多技术文章

Ollama重大升级:支持结构化输出

[复制链接]
链载Ai 显示全部楼层 发表于 2025-12-2 11:56:45 |阅读模式 打印 上一主题 下一主题


Ollama现在开始支持结构化输出,能够将模型的输出限定为JSON模式所定义的特定格式。Ollama的Python和JavaScript库已更新,以支持结构化输出。

12月6日Ollama发布了新的0.5版本,开始支持模型结果的结构化输出,能够将模型的输出限定为JSON模式所定义的特定格式。Ollama的Python和JavaScript库已更新,以支持结构化输出。

Ollama结构化输出的情形包括:

• 从文档中解析数据

• 从图像中提取数据

• 构建所有语言模型的回复结构

• 比JSON模式更具可靠性和一致性

01

开始使用

Ollama的结构化输出需要更新到0.5及以上版本。请首先更新Ollama以及Python或JavaScript库。

要将结构化输出传递给模型,可以在cURL请求中使用“格式”(format)参数,或者在Python或JavaScript库中使用“格式”参数。

02


通过CURL使用

可以简单的通过CURL命令调用模型,并使用结构化输出。

curl-XPOSThttp://localhost:11434/api/chat-H"Content-Type:application/json"-d'{"model":"llama3.1","messages":[{"role":"user","content":"TellmeaboutCanada."}],"stream":false,"format":{"type":"object","properties":{"name":{"type":"string"},"capital":{"type":"string"},"languages":{"type":"array","items":{"type":"string"}}},"required":["name","capital","languages"]}}'

模型的响应将按照请求中JSON模式所定义的格式返回。

{"capital":"Ottawa","languages":["English","French"],"name":"Canada"}


03‍


使用Python库

使用Ollama的Python库时,将schema作为JSON对象传递给“foramt”参数,可以以字典(dict)形式传递,或者使用“Pydantic”(推荐)通过“model_json_schema()”方法对模式进行序列化。

fromollamaimportchatfrompydanticimportBaseModelclassCountry(BaseModel):name:strcapital:strlanguages:list[str]response=chat(messages=[{'role':'user','content':'TellmeaboutCanada.',}],model='llama3.1',format=Country.model_json_schema(),)country=Country.model_validate_json(response.message.content)print(country)

同样,模型的响应将按照请求中JSON模式所定义的格式返回。

name='Canada'capital='Ottawa'languages=['English','French']


04


使用JavaScript库

使用OllamaJavaScript库时,将schema作为JSON对象传递给“format”参数,可以以对象(object)形式传递,或者使用“Zod”(推荐)通过“zodToJsonSchema()”方法对模式进行序列化。

importollamafrom'ollama';import{z}from'zod';import{zodToJsonSchema}from'zod-to-json-schema';constCountry=z.object({name:z.string(),capital:z.string(),languages:z.array(z.string()),});constresponse=awaitollama.chat({model:'llama3.1',messages:[{role:'user',content:'TellmeaboutCanada.'}],format:zodToJsonSchema(Country),});constcountry=Country.parse(JSON.parse(response.message.content));console.log(country);

毫无例外,模型的响应将按照请求中JSON模式所定义的格式返回。

{name:"Canada",capital:"Ottawa",languages:["English","French"],}


05


示例

1. 数据提取:

为了从文本中提取结构化数据,需要定义一个schema来代表信息。然后模型就可以抽取信息并将数据以在定义的schema中的JSON格式返回。

fromollamaimportchatfrompydanticimportBaseModelclassPet(BaseModel):name:stranimal:strage:intcolor:str|Nonefavorite_toy:str|NoneclassPetList(BaseModel):pets:list[Pet]response=chat(messages=[{'role':'user','content':'''Ihavetwopets.AcatnamedLunawhois5yearsoldandlovesplayingwithyarn.Shehasgreyfur.Ialsohavea2yearoldblackcatnamedLokiwholovestennisballs.''',}],model='llama3.1',format=PetList.model_json_schema(),)pets=PetList.model_validate_json(response.message.content)print(pets)

示例输出结果:

pets=[Pet(name='Luna',animal='cat',age=5,color='grey',favorite_toy='yarn'),Pet(name='Loki',animal='cat',age=2,color='black',favorite_toy='tennisballs')]


2. 图像提取:

结构化输出还可以与视觉模型一起使用。例如,下面的代码使用llama3.2-vision来描述以下图片,并返回一个结构化的输出。

fromollamaimportchatfrompydanticimportBaseModelclassObject(BaseModel):name:strconfidence:floatattributes:strclassImageDescription(BaseModel):summary:strobjectsist[Object]scene:strcolorsist[str]time_of_dayiteral['Morning','Afternoon','Evening','Night']settingiteral['Indoor','Outdoor','Unknown']text_content:Optional[str]=Nonepath='path/to/image.jpg'response=chat(model='llama3.2-vision',format=ImageDescription.model_json_schema(),#Passintheschemafortheresponsemessages=[{'role':'user','content':'Analyzethisimageanddescribewhatyousee,includinganyobjects,thescene,colorsandanytextyoucandetect.','images':[path],},],options={'temperature':0},#Settemperatureto0formoredeterministicoutput)image_description=ImageDescription.model_validate_json(response.message.content)print(image_description)

示例输出结果:

summary='Apalmtreeonasandybeachwithbluewaterandsky.'objects=[Object(name='tree',confidence=0.9,attributes='palmtree'),Object(name='beach',confidence=1.0,attributes='sand')],scene='beach',colors=['blue','green','white'],time_of_day='Afternoon'setting='Outdoor'text_content=None


3. 兼容OpenAI:

fromopenaiimportOpenAIimportopenaifrompydanticimportBaseModelclient=OpenAI(base_url="http://localhost:11434/v1",api_key="ollama")classPet(BaseModel):name:stranimal:strage:intcolor:str|Nonefavorite_toy:str|NoneclassPetList(BaseModel):pets:list[Pet]try:completion=client.beta.chat.completions.parse(temperature=0,model="llama3.1:8b",messages=[{"role":"user","content":'''Ihavetwopets.AcatnamedLunawhois5yearsoldandlovesplayingwithyarn.Shehasgreyfur.Ialsohavea2yearoldblackcatnamedLokiwholovestennisballs.'''}],response_format=PetList,)pet_response=completion.choices[0].messageifpet_response.parsed:print(pet_response.parsed)elifpet_response.refusal:print(pet_response.refusal)exceptExceptionase:iftype(e)==openai.LengthFinishReasonError:print("Toomanytokens:",e)passelse:print(e)pass


06


下一步计划

• 公开对数几率(logits)以实现可控生成

• 提升结构化输出的性能和准确性

• 对采样进行GPU加速

• 提供JSON模式之外的其他格式支持

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

链载AI是专业的生成式人工智能教程平台。提供Stable Diffusion、Midjourney AI绘画教程,Suno AI音乐生成指南,以及Runway、Pika等AI视频制作与动画生成实战案例。从提示词编写到参数调整,手把手助您从入门到精通。
  • 官方手机版

  • 微信公众号

  • 商务合作

  • Powered by Discuz! X3.5 | Copyright © 2025-2025. | 链载Ai
  • 桂ICP备2024021734号 | 营业执照 | |广西笔趣文化传媒有限公司|| QQ