openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
examples/responses/structured_outputs.py
55lines · modeblame
2954945eRobert Craigie1 years ago | 1 | from typing import List |
| 2 | | |
| 3 | import rich | |
| 4 | from pydantic import BaseModel | |
| 5 | | |
| 6 | from openai import OpenAI | |
| 7 | | |
| 8 | | |
| 9 | class Step(BaseModel): | |
| 10 | explanation: str | |
| 11 | output: str | |
| 12 | | |
| 13 | | |
| 14 | class MathResponse(BaseModel): | |
| 15 | steps: List[Step] | |
| 16 | final_answer: str | |
| 17 | | |
| 18 | | |
| 19 | client = OpenAI() | |
| 20 | | |
| 21 | rsp = client.responses.parse( | |
| 22 | input="solve 8x + 31 = 2", | |
| 23 | model="gpt-4o-2024-08-06", | |
| 24 | text_format=MathResponse, | |
| 25 | ) | |
| 26 | | |
| 27 | for output in rsp.output: | |
| 28 | if output.type != "message": | |
| 29 | raise Exception("Unexpected non message") | |
| 30 | | |
| 31 | for item in output.content: | |
| 32 | if item.type != "output_text": | |
| 33 | raise Exception("unexpected output type") | |
| 34 | | |
| 35 | if not item.parsed: | |
| 36 | raise Exception("Could not parse response") | |
| 37 | | |
| 38 | rich.print(item.parsed) | |
| 39 | | |
| 40 | print("answer: ", item.parsed.final_answer) | |
| 41 | | |
| 42 | # or | |
| 43 | | |
| 44 | message = rsp.output[0] | |
| 45 | assert message.type == "message" | |
| 46 | | |
| 47 | text = message.content[0] | |
| 48 | assert text.type == "output_text" | |
| 49 | | |
| 50 | if not text.parsed: | |
| 51 | raise Exception("Could not parse response") | |
| 52 | | |
| 53 | rich.print(text.parsed) | |
| 54 | | |
| 55 | print("answer: ", text.parsed.final_answer) |