POST/v1/chat/completions{"model":"gpt-4o-2024-08-06","messages":[{"role":"system","content":"Youareahelpfulmathtutor."},{"role":"user","content":"solve8x+31=2"}],"response_format":{"type":"json_schema","json_schema":{"name":"math_response","strict":true,"schema":{"type":"object","properties":{"steps":{"type":"array","items":{"type":"object","properties":{"explanation":{"type":"string"},"output":{"type":"string"}},"required":["explanation","output"],"additionalProperties":false}},"final_answer":{"type":"string"}},"required":["steps","final_answer"],"additionalProperties":false}}}}输出如下:
{"steps":[{"explanation":"Subtract31frombothsidestoisolatethetermwithx.","output":"8x+31-31=2-31"},{"explanation":"Thissimplifiesto8x=-29.","output":"8x=-29"},{"explanation":"Dividebothsidesby8tosolveforx.","output":"x=-29/8"}],"final_answer":"x=-29/8"}虽然API request看上去很复杂,比如Python官方包做了封装,实现上述功能的代码如下:
from pydantic import BaseModelfrom openai import OpenAIclass Step(BaseModel):explanation: stroutput: strclass MathResponse(BaseModel):steps: list[Step]final_answer: strclient = OpenAI()completion = client.beta.chat.completions.parse(model="gpt-4o-2024-08-06",messages=[{"role": "system", "content": "You are a helpful math tutor."},{"role": "user", "content": "solve 8x + 31 = 2"},],response_format=MathResponse,)message = completion.choices[0].messageif message.parsed:print(message.parsed.steps)print(message.parsed.final_answer)else:print(message.refusal)
此外OpenAI特别强调了结构化输出功能是安全的,必须符合现有的安全策略,所以特别在API中新增加了一个输出字段refusal,用于描述是不符合JSON还是不安全!
这篇文章描述了如何使用结构化输出功能,其实OpenAI也介绍了如何实现该功能,这个有机会再讲,对于理解模型训练很有帮助!
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |