Generative AI · Intermediate level

Intermediate level · Module 4: Building Applications with LLM APIs · Lesson 2 of 3

Keys, Streaming, Errors and Rate Limits

Learners keep keys out of code, stream long responses to users, and handle timeouts, provider errors and rate limits with retries.

In this lesson you will

  • Manage API keys securely
  • Handle streaming, errors and rate limits

Key concepts

environment variables.gitignorestreamingtimeouts and retriesHTTP 429

The lesson

Read keys from environment variables or an ignored .env file; never commit them or paste them into shared notebooks. Rotate a key immediately if it is exposed.

Streaming returns tokens as they are generated, so users see progress on slow connections. Set timeouts on every request.

Retry temporary failures (timeouts, server errors, rate-limit responses such as HTTP 429) with increasing waits and a maximum number of attempts; do not retry invalid requests.

Step by step

  1. Move keys to environment variables and add .env to .gitignore.
  2. Add streaming output to the interface.
  3. Add timeouts and retries with back-off.
  4. Test with a simulated rate-limit error.

Practice activity

Harden the model interface with secure keys, streaming, timeouts and retries.

Expected result: No keys in code, visible streaming, and graceful handling of simulated failures.

Check your understanding

  1. Where should API keys be stored?

    Show answer

    In environment variables or an ignored .env file.

  2. Which errors should be retried?

    Show answer

    Temporary ones such as timeouts, server errors and rate limits.

Further learning

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.