How to use OpenAI stream object?
- User
How to use OpenAI stream object?
Assistant
The OpenAI stream object is used to handle streaming responses from the OpenAI API. Here's an example of how to use it:
pythonimport openai # Create a completion completion = openai.Completion() # Create a stream stream = completion.create( model="text-davinci-003", prompt="Write a story about a character who discovers a hidden world.", max_tokens=100, stream=True, ) # Iterate over the stream for chunk in stream: print(chunk.choices[0].delta.content)In this example, the
createmethod of theCompletionobject is used to create a completion with thestreamparameter set toTrue. This returns a stream object that can be iterated over to retrieve the completion results.You can also use the
asyncversion of the client to stream completions:pythonimport asyncio import openai # Create an async completion completion = openai.AsyncCompletion() # Create a stream async def main(): stream = await completion.create( model="text-davinci-003", prompt="Write a story about a character who discovers a hidden world.", max_tokens=100, stream=True, ) # Iterate over the stream async for chunk in stream: print(chunk.choices[0].delta.content) asyncio.run(main())In this example, the
createmethod of theAsyncCompletionobject is used to create a completion with thestreamparameter set toTrue. This returns a stream object that can be iterated over to retrieve the completion results.You can also use the
with_raw_responsemethod to get the raw response from the API:python
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.