Skip to content

Instantly share code, notes, and snippets.

@companje
Last active June 1, 2024 10:02
Show Gist options
  • Save companje/9fbdf172fbde0c9b6d8ac0ad99306901 to your computer and use it in GitHub Desktop.
Save companje/9fbdf172fbde0c9b6d8ac0ad99306901 to your computer and use it in GitHub Desktop.
parse ChatGPT API incoming streaming json objects with ijson
# thanks: https://til.simonwillison.net/json/ijson-stream
import json,openai,ijson
client = openai.OpenAI()
response = client.chat.completions.create(
model='gpt-4o',
response_format={ "type": "json_object" },
messages=[
{'role': 'user', 'content': 'count to 15 and return json like {"items": [{"action":"setValue","range":"A1","value":"1"}\n{"action":"setValue","range":"A2","value":"2"}, ... ]}'}
],
temperature=0,
stream=True
)
events = ijson.sendable_list()
coro = ijson.items_coro(events, "items.item")
seen_events = set()
for chunk in response:
msg = chunk.choices[0].delta.content
if msg:
coro.send(msg.encode("utf-8"))
if events:
unseen_events = [e for e in events if json.dumps(e) not in seen_events]
if unseen_events:
for event in unseen_events:
seen_events.add(json.dumps(event))
print(json.dumps(event))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment