openai/openai-python

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.66.2

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/parsing_stream.py

42lines · 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
21with client.beta.chat.completions.stream(
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) as stream:
29for event in stream:
30if event.type == "content.delta":
31print(event.delta, end="", flush=True)
32elif event.type == "content.done":
33print("\n")
34if event.parsed is not None:
35print(f"answer: {event.parsed.final_answer}")
36elif event.type == "refusal.delta":
37print(event.delta, end="", flush=True)
38elif event.type == "refusal.done":
39print()
40
41print("---------------")
42rich.print(stream.get_final_completion())