Skip to content

Instantly share code, notes, and snippets.

@mattcollins
Last active May 12, 2024 21:46
Show Gist options
  • Save mattcollins/62fcb8d15a001d5b4e5c9fb86aad4f8e to your computer and use it in GitHub Desktop.
Save mattcollins/62fcb8d15a001d5b4e5c9fb86aad4f8e to your computer and use it in GitHub Desktop.
Example of extracting multiple values from a streamed OpenAI chat response
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)
@mattcollins
Copy link
Author

mattcollins commented May 12, 2024

Here's some sample output from running the script:

{}
{}
{}
{}
{}
{'a': ''}
{'a': 'John'}
{'a': 'John Doe'}
{'a': 'John Doe'}
{'a': 'John Doe'}
{'a': 'John Doe'}
{'a': 'John Doe'}
{'a': 'John Doe'}
{'a': 'John Doe', 'b': ''}
{'a': 'John Doe', 'b': 'Bob'}
{'a': 'John Doe', 'b': 'Bob Smith'}
{'a': 'John Doe', 'b': 'Bob Smith'}
{'a': 'John Doe', 'b': 'Bob Smith'}
{'a': 'John Doe', 'b': 'Bob Smith'}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment