openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.80.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/parsing.py

36lines · modeblame

bf1ca86cRobert Craigie1 years ago1from typing import List
2
3import rich
4from pydantic import BaseModel
5
6from openai import OpenAI
7
8
9class Step(BaseModel):
10explanation: str
11output: str
12
13
14class MathResponse(BaseModel):
15steps: List[Step]
16final_answer: str
17
18
19client = OpenAI()
20
21completion = client.beta.chat.completions.parse(
22model="gpt-4o-2024-08-06",
23messages=[
24{"role": "system", "content": "You are a helpful math tutor."},
25{"role": "user", "content": "solve 8x + 31 = 2"},
26],
27response_format=MathResponse,
28)
29
30message = completion.choices[0].message
31if message.parsed:
32rich.print(message.parsed.steps)
33
34print("answer: ", message.parsed.final_answer)
35else:
36print(message.refusal)