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
- Python
- Visual Studio Code
- Anthropic Console account and API key
- Internet access and available API credits
4. Create your project
Open the VS Code terminal and verify Python:
python --versionCreate a folder, navigate into it, and add a file named main.py:
mkdir claude-first-app
cd claude-first-app5. Install the Anthropic Python SDK
The SDK provides a convenient Python client for calling the API:
python -m pip install --upgrade anthropic6. 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:
$env:ANTHROPIC_API_KEY="YOUR_API_KEY_HERE"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:
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)Understanding the request
| Field | Purpose |
|---|---|
model | Selects the Claude model |
max_tokens | Maximum generated output tokens |
messages | Messages supplied to Claude |
response.content | Returned content blocks, including text |
8. Run the application
Execute the Python file:
python main.pyYou 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:
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:
python main.pyTry 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
| Issue | What to check |
|---|---|
| ModuleNotFoundError | Install the SDK into the Python environment you are using |
| 401 authentication error | Verify the API key |
| 404 model error | Verify model ID and account access |
| 429 rate limit | Check usage limits and retry guidance |
| Missing API key | Set the environment variable in the current terminal |
| KeyboardInterrupt | Usually 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
Post a Comment