Claude With The Anthropic Api
← All lessons
Lesson 05Claude With The Anthropic Api

Making a request

Summary audio

No audio recap for this lesson.

Study notes

Setup Steps

  • Step 1: Install packages in Jupyter notebook using %pip install anthropic python-dotenv
  • Ignore red syntax errors from the percent sign in VS Code
  • Step 2: Store API key securely using . env file
  • Create a . env file in the same directory as your notebook
  • Format: ANTHROPIC_API_KEY="your-key-here"
  • Add . env to version control ignore file (e. g. , . gitignore) to prevent accidental commits
  • Step 3: Create API client and declare model variable
  • Use the anthropic package to instantiate a client
  • Store model name (e. g. , "claude-sonnet") in a variable
  • Step 4: Make your first request using the client

The create() Function

The core function for accessing Claude is client. messages. create() with three required keyword arguments:

  • model: Name of the model to run (string variable defined earlier)
  • max_tokens: Maximum number of tokens Claude can generate
  • Acts as a safety mechanism to prevent excessive output
  • Claude doesn't target this number; it generates appropriate-length responses
  • Generation stops automatically if limit is reached
  • messages: List of message objects representing the conversation

Message Types

  • User messages: Contain text authored by a person (developer or end user)
  • Format: dictionary with role: "user" and content: "your text"
  • Assistant messages: Contain text generated by Claude
  • Returned in API responses

Accessing the Response

  • The response object contains nested data; use message. content[0]. text to extract just the generated text
  • Ignore other properties in the response object unless specifically needed

Takeaways

  • Install the anthropic and python-dotenv packages, store your API key in a . env file, and create a client to make requests
  • Use client. messages. create() with three required arguments: model, max_tokens (safety limit for output length), and messages (list of message objects)
  • Format messages as dictionaries with role ("user" or "assistant") and content fields; extract the generated text from the response using message. content[0]. text
Flashcards 8 cards
Question
click to reveal · ←/→
Answer
click to flip back
Export to Anki (.tsv) ↓
Knowledge check 1 questions