openai/openai-python
Publicmirrored from https://github.com/openai/openai-pythonAvailable
examples/parsing.py
36lines · modecode
| 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 | completion = client.chat.completions.parse( |
| 22 | model="gpt-4o-2024-08-06", |
| 23 | messages=[ |
| 24 | {"role": "system", "content": "You are a helpful math tutor."}, |
| 25 | {"role": "user", "content": "solve 8x + 31 = 2"}, |
| 26 | ], |
| 27 | response_format=MathResponse, |
| 28 | ) |
| 29 | |
| 30 | message = completion.choices[0].message |
| 31 | if message.parsed: |
| 32 | rich.print(message.parsed.steps) |
| 33 | |
| 34 | print("answer: ", message.parsed.final_answer) |
| 35 | else: |
| 36 | print(message.refusal) |