链载Ai

标题: Ollama重大升级:支持结构化输出 [打印本页]

作者: 链载Ai    时间: 2025-12-2 11:56
标题: Ollama重大升级:支持结构化输出


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 (http://www.lianzai.com/) Powered by Discuz! X3.5