Last active
May 12, 2024 21:46
-
-
Save mattcollins/62fcb8d15a001d5b4e5c9fb86aad4f8e to your computer and use it in GitHub Desktop.
Example of extracting multiple values from a streamed OpenAI chat response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from langchain_openai import ChatOpenAI | |
from partial_json_parser import loads | |
def update_frontend(json): | |
# Here's where you'd have code to update your front-end. | |
# For now, we're printing the JSON to the console to | |
# see what it consists of. | |
print(json) | |
llm = ChatOpenAI( | |
streaming=True | |
) | |
# For test purposes I'm asking GPT-4 to return a specific JSON object. | |
# You'd replace this with your own prompt. | |
content = """ | |
Return the following JSON object: | |
{ | |
"a": "John Doe", | |
"b": "Bob Smith" | |
} | |
""" | |
stream = llm.stream(content) | |
content_so_far = "" | |
for chunk in stream: | |
content_so_far += chunk.content | |
if content_so_far != "": | |
json = loads(content_so_far) | |
update_frontend(json) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's some sample output from running the script: