Calling an LLM from Python

20 min read

Every chatbot, summariser and AI agent starts with one small step. A Python program sends some messages to a language model and reads the reply. This lesson is the bridge from Python basics into LLM engineering. You will see the real code for calling the Anthropic API. Then you will practise the skills around it: building messages, keeping history, counting cost, retrying after errors and reading JSON. For this practice you will use a fake model that runs right here in your browser.

New words

API call
A request your program sends to a service, and its reply.
API key
A secret code for your account, like a UPI PIN. Keep it secret.
SDK
A Python package that makes calling an API easy.
Token
A small piece of text. You pay for tokens.
Streaming
Showing the reply piece by piece while the model writes it.
Rate limit
The error you get when you send too many requests too fast.
Exponential backoff
Waiting longer after each failed try: 1, 2, 4 seconds.

What you will learn

  1. What an LLM API call is
  2. API key and installing the SDK
  3. The messages format and the response
  4. Conversation history and streaming
  5. Errors and retries
  6. Cost awareness and safe JSON
  7. Try it: watch a request and response
  8. Common mistakes
  9. Explain it to a friend
  10. Key takeaways

10 quiz questions at the end.

Start this lesson

The full lesson, with interactive demos and the quiz, opens after you sign in with Google. It is free.

All lessons · Back to the roadmap