How to use OpenAI stream object?
- User
How to use OpenAI stream object?
Assistant
Based on the provided repository content, I'll explain how to use OpenAI's streaming functionality for API responses.
Here are the key ways to use streaming:
- Basic Streaming with Chat Completions:
pythonfrom openai import OpenAI client = OpenAI() # Create a streaming response stream = client.chat.completions.create( messages=[{ "role": "user", "content": "Say this is a test", }], model="gpt-4", stream=True # Enable streaming ) # Method 1: Iterate over the stream for chunk in stream: # Access the content from the delta print(chunk.choices[0].delta.content or "", end="")- Async Streaming:
pythonimport asyncio from openai import AsyncOpenAI async def main(): client = AsyncOpenAI() stream = await client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": "Say this is a test"}], stream=True ) async for chunk in stream: print(chunk.choices[0].delta.content or "", end="") asyncio.run(main())- Manual Stream Control:
python# Synchronous stream = client.completions.create( model="gpt-3.5-turbo-instruct", prompt="1,2,3,", max_tokens=5, temperature=0, stream=True ) # Get first response manually first = next(stream) print(f"got response data: {first.to_json()}") # Continue with rest of stream for data in stream: print(data.to_json()) # Async version async def manual_stream(): stream = await client.completions.create( model="gpt-3.5-turbo-instruct", prompt="1,2,3,", max_tokens=5, temperature=0, stream=True ) # Get first response manually first = await stream.__anext__() print(f"got response data: {first.to_json()}") # Continue with rest of stream async for data in stream: print(data.to_json())
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.