Skip to main content

Claude AI Tutorial for Beginners: Build Your First AI Application Using Python

Introduction

Want to build your first AI-powered application? In this step-by-step beginner tutorial, we will integrate Claude AI with Python using the Anthropic API, send a message, display its answer, and upgrade the example into an interactive chatbot. Every code block includes a Copy Code button.

What you will learn

  • What Claude AI is and how its API works
  • Setting up Python, VS Code and the Anthropic SDK
  • Using an API key securely
  • Sending a request and reading its response
  • Building a chatbot with conversation history

1. What is Claude AI?

Claude is a family of large language models (LLMs) developed by Anthropic. It can explain concepts, help write code, summarize documents and power custom AI applications. The Claude chat interface lets people chat directly; the API lets software communicate with Claude programmatically.

2. How does Claude API integration work?

User → Python application → Anthropic API → Claude model → API response → User. Our program sends a message to Claude and extracts the returned text. We do not need to train our own model.

3. Prerequisites

API usage can incur charges. A Claude chat subscription does not automatically include API credits. Never publish your real API key.

4. Create your project

Open the VS Code terminal and verify Python:

Terminal — Python version
python --version

Create a folder, navigate into it, and add a file named main.py:

Terminal — project setup
mkdir claude-first-app
cd claude-first-app

5. Install the Anthropic Python SDK

The SDK provides a convenient Python client for calling the API:

Terminal — install SDK
python -m pip install --upgrade anthropic

6. Configure your API key

Create an API key in the Anthropic Console. Set it in the same terminal session where you will run your application:

Windows PowerShell
$env:ANTHROPIC_API_KEY="YOUR_API_KEY_HERE"
macOS / Linux
export ANTHROPIC_API_KEY="YOUR_API_KEY_HERE"

Replace the placeholder privately. Avoid committing secrets to GitHub or showing them in screenshots.

7. Build your first Claude AI application

Copy this complete code into main.py:

main.py — first Claude request
import os
from anthropic import Anthropic

api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
    raise RuntimeError("Please set ANTHROPIC_API_KEY.")

client = Anthropic(api_key=api_key)
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=500,
    messages=[
        {"role": "user", "content": "Explain Generative AI in simple words."}
    ]
)
for item in response.content:
    if item.type == "text":
        print(item.text)
Model note: This example uses a model identifier from the tutorial. Check Anthropic’s current model documentation and use an available model for your account before running it.

Understanding the request

FieldPurpose
modelSelects the Claude model
max_tokensMaximum generated output tokens
messagesMessages supplied to Claude
response.contentReturned content blocks, including text

8. Run the application

Execute the Python file:

Terminal — run your app
python main.py

You should see Claude explain Generative AI. The exact wording may vary.

9. Bonus: Build an interactive chatbot

The first version uses a fixed question. Let’s accept questions continuously, show each answer, and maintain conversation history until the user types exit. Replace main.py with:

main.py — complete interactive chatbot
import os
from anthropic import Anthropic

api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
    raise RuntimeError("Please set ANTHROPIC_API_KEY.")

client = Anthropic(api_key=api_key)
MODEL = "claude-sonnet-4-5"
conversation = []

print("DigiTech Bites AI Assistant — type 'exit' to quit")

while True:
    question = input("\nYou: ").strip()
    if question.lower() in ("exit", "quit"):
        print("Goodbye!")
        break
    if not question:
        continue

    conversation.append({"role": "user", "content": question})
    try:
        response = client.messages.create(
            model=MODEL,
            max_tokens=500,
            system="Explain technical topics in simple language.",
            messages=conversation
        )
        answer = "\n".join(
            part.text for part in response.content if part.type == "text"
        )
        if not answer:
            conversation.pop()
            print("No text response received.")
            continue
        print("\nClaude:", answer)
        conversation.append({"role": "assistant", "content": answer})
    except Exception as exc:
        conversation.pop()
        print("API error:", exc)

Run the chatbot:

Terminal — start chatbot
python main.py

Try asking “What is Python?” followed by “Can you give me a simple example?” The second API request includes the earlier exchange.

10. How does conversation history work?

The Claude Messages API is stateless: it does not automatically remember previous API calls. We append user questions and assistant answers to a Python list and send that list with the next request. This beginner example stores history only while the program runs. A production app should manage context length, token cost, retries, logging, privacy and secure storage.

11. Common errors and troubleshooting

IssueWhat to check
ModuleNotFoundErrorInstall the SDK into the Python environment you are using
401 authentication errorVerify the API key
404 model errorVerify model ID and account access
429 rate limitCheck usage limits and retry guidance
Missing API keySet the environment variable in the current terminal
KeyboardInterruptUsually means Ctrl+C stopped the program

12. What can you build next?

Try a document summarizer, code review assistant, customer support bot, travel assistant with tool calling, or an enterprise knowledge assistant using retrieval-augmented generation (RAG).

Conclusion

You have now connected Python to Claude, sent your first API request, read a response and built a simple interactive chatbot. In our next DigiTech Bites tutorial, we will explore API request and response structure, roles, tokens and model parameters.

DigiTech Bites — Technology Explained. Simply.
www.digitechbites.in

Comments

Popular posts from this blog

Sitecore Publishing target and Solr Configuration

Creating a new publishing target is very helpful if your Sitecore environment is setup in multiple content delivery servers. We can publish data from Master database to one or more publishing target databases. Main thing to notice here is Master database contains all versions of any content or assets while publishing target database contains single latest version for each language.      This post aims to provide systematic instructions to set up publishing target. It comprises of a target database (where the content will be published) and publishing target definition item in master database that points to that target database.             Post creation of publishing target need to take care of Solr configuration. This post cove master slave Solr configuration and onPublishEndAsync strategy. We are using 1 Solr Master instance and 6 Slave instance (2-EU, 2-Ap, 2- NA).     1   So...

Setup Sitecore Habitat v9.0 project in simple way

In this article , I would describe how to setup the Sitecore habitat V9.0 project with Sitecore Experience Platform 9.0 rev in very simple way. I used below system configuration to setup this project: 1. Windows 10 (32/64-bit) 2. IIS 10.0 3. .NET Framework 4.6.2 4. Microsoft Visual Studio 2017 5. Microsoft SQL Server 2017 6. Solr 6.6.2 7. Microsoft PowerShell® version 5.0 8. Web Platform Installer 5.0. 9. Web Deploy 3.6 for Hosting Servers 10. Node-v8.9.4-x64 Follow below steps to setup the project. A).   Habitat require Sitecore instance. Setup the clean Sitecore 9.0 instance. Ex : http://demo.local.com , Directory location : C:\inetpub\wwwroot\demo.local.com   For more info visit -   https://dev.sitecore.net/ B). Download the Habitat V9.0 project from Github site :  https://github.com/Sitecore/Habitat/     Note  :  When you download the packages, it is possible that the .ZIP packages are marked as blocke...

Web Deploy setup and configuration with Sitecore

Web Deploy empowers Visual Studio and WebMatrix to help developers streamline the deployment of Web applications to Microsoft IIS Web servers or to Microsoft Azure Websites. In addition, integration with Web Platform Installer allows developers to simply and easily install community webapplications.   This post describe the installation of Web Deploy and Configuration with Sitecore instance.  This post will be very useful if you want to sync your Sitecore media items with all of the CD's environment (Distributed environment) . In one of my previous project, I was keeping all the media items in file system and synchronizing all the files from CM to Cd's server. This solution is tested with 1 CMS and 6 CD's server (2-EU, 2- NA, 2- AP) with more than 5 Lakh files.  1.       Software Pre-requisites           a.       OS – Window 7/ Windows Server 2008 R2 Enterprise       ...