openai/openai-python

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.99.8

Branches

Tags

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

Clone

HTTPS

Download ZIP

examples/responses/background_streaming.py

48lines · modeblame

f588695fstainless-app[bot]1 years ago1#!/usr/bin/env -S rye run python
2from typing import List
3
4import rich
5from pydantic import BaseModel
6
7from openai import OpenAI
8
9
10class Step(BaseModel):
11explanation: str
12output: str
13
14
15class MathResponse(BaseModel):
16steps: List[Step]
17final_answer: str
18
19
20client = OpenAI()
21id = None
22with client.responses.stream(
23input="solve 8x + 31 = 2",
24model="gpt-4o-2024-08-06",
25text_format=MathResponse,
26background=True,
27) as stream:
28for event in stream:
29if event.type == "response.created":
30id = event.response.id
31if "output_text" in event.type:
32rich.print(event)
33if event.sequence_number == 10:
34break
35
36print("Interrupted. Continuing...")
37
38assert id is not None
39with client.responses.stream(
40response_id=id,
41starting_after=10,
42text_format=MathResponse,
43) as stream:
44for event in stream:
45if "output_text" in event.type:
46rich.print(event)
47
48rich.print(stream.get_final_response())