Back to Documentation

Streaming Response Handling

Implement real-time streaming output effects

Code Examples

// Using Server-Sent Events to handle streaming responses
const evtSource = new EventSource('/api/stream');

evtSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  if (data.choices[0].delta?.content) {
    // Display content in real-time
    document.getElementById('output').innerHTML += data.choices[0].delta.content;
  }
  
  if (data.choices[0].finish_reason === 'stop') {
    evtSource.close();
  }
};

// Python streaming handling
import openai

stream = openai.ChatCompletion.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.get('content'):
        print(chunk.choices[0].delta['content'], end='', flush=True)

Getting Started

Complete integration in 5 minutes

Best Practices

Follow recommended development patterns

Technical Support

Get professional help