How to Build Your Own AI Agent with Claude API and Run It for Free in 2026
MU
Muhammed Rafeeq
Published: 8 Jun 2026
9 min read
A complete step-by-step tutorial for building a real AI agent using the Claude API — from zero to deployed, with free hosting options for Indian developers.
Building your own AI agent used to require a PhD and a research lab. In 2026, it requires a laptop, an internet connection, and about two hours. In this tutorial, we will build a research agent from scratch using the Anthropic Claude API — an agent that accepts a topic, searches for information, synthesises a structured report, and saves it to a file. By the end, you will understand the core architecture of AI agents and have a working project you can extend. This tutorial is designed for Indian developers with basic Python knowledge but no prior AI or ML experience.
Key Takeaways
You will build a working AI research agent using Python and the Claude API
The agent will accept a topic, gather information, and produce a structured markdown report
Total cost: ₹0 using Claude's free API tier (up to 5 requests/minute)
You will learn: API calls, tool use, prompt design, and agent loops
The final code is under 100 lines and fully extensible
5 minaverage time to get your first Claude API response workingThe Anthropic API has one of the simplest onboarding flows among major AI providers — most developers make their first successful API call within 5 minutes of getting their key.
Prerequisites
You need: Python 3.9 or higher installed, a free Anthropic account (sign up at console.anthropic.com), basic Python familiarity (variables, functions, loops). No ML or AI experience required.
Step 1: Set Up Your Environment
Before writing any agent code, we need a clean Python environment and the Anthropic SDK installed. Using a virtual environment is best practice — it keeps your project dependencies isolated and prevents version conflicts. Open your terminal (Command Prompt or PowerShell on Windows, Terminal on Mac/Linux) and run the following commands. The entire setup should take less than five minutes.
bash
setup.sh
# Create a new project foldermkdir my-ai-agent && cd my-ai-agent
# Create a virtual environment
python -m venv venv
# Activate it (Windows)
venv\Scripts\activate
# Activate it (Mac/Linux)source venv/bin/activate
# Install the Anthropic SDK
pip install anthropic
# Verify installation
python -c "import anthropic; print('SDK installed successfully')"
Windows Users
If you get a 'python not found' error, try using 'py' instead of 'python'. If pip fails, ensure Python was added to your PATH during installation. Reinstall Python from python.org and check the 'Add to PATH' checkbox.
Step 2: Get Your API Key and Set It Up Securely
Your API key is like a password — never hardcode it in your script or commit it to GitHub. We will store it in a .env file and load it securely. Go to console.anthropic.com, sign up for a free account, and navigate to API Keys in the left sidebar. Click 'Create Key', name it 'my-agent', and copy the key immediately — you will not be able to see it again. Then create a .env file in your project folder and add your key. We will use python-dotenv to load it automatically.
bash
.env
# .env file — never commit this to git!
ANTHROPIC_API_KEY=sk-ant-api03-your-key-here
bash
# Install python-dotenv
pip install python-dotenv
# Add .env to .gitignore to keep your key safeecho".env" >> .gitignore
Never Expose Your API Key
If you accidentally commit your API key to a public GitHub repo, revoke it immediately at console.anthropic.com and create a new one. Exposed keys can be exploited within minutes by automated scrapers.
Step 3: Make Your First API Call
Before building the full agent, let us verify that your setup works with a simple API call. Create a file called test_api.py and run it. This confirms your API key is valid, the SDK is installed correctly, and you can receive responses from Claude. The free tier allows up to 5 requests per minute and generous daily limits — more than enough for development and light production use.
python
test_api.py
import anthropic
from dotenv import load_dotenv
load_dotenv()
client = anthropic.Anthropic() # Reads ANTHROPIC_API_KEY from environment
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "What are the top 3 reasons Indian developers should learn about AI agents in 2026? Answer in 3 bullet points."}
]
)
print(message.content[0].text)
Step 4: Understand the Agent Architecture
An AI agent follows a loop: perceive → think → act → repeat. In our research agent, the loop works like this: the agent receives a research topic from the user, it thinks about what information it needs, it calls a 'tool' (a Python function we define) to gather that information, it receives the tool's output, reasons about what to do next, and either calls another tool or produces a final answer. This 'think-then-act' loop is called an agentic loop, and it is the foundational pattern behind all AI agents from simple scripts to complex autonomous systems.
1
User provides a research topic to the agent
2
Claude analyses the topic and decides which tools to call
3
Agent executes the tool (e.g., web search or file read)
4
Tool result is returned to Claude as a new message
5
Claude decides whether to call more tools or write the final report
6
Final report is saved to a markdown file
Step 5: Build the Agent with Tool Use
Claude's tool use feature (also called function calling) lets Claude decide when to call external functions you define. You describe the tools available, Claude decides which one to call and with what parameters, your code executes the function, and the result is fed back to Claude. In our agent, we will define two tools: one that simulates a web search (in production you would integrate a real search API like Tavily or SerpAPI) and one that saves the final report to a file. This pattern is extensible to any real-world action.
python
agent.py
import anthropic
import json
from dotenv import load_dotenv
from datetime import datetime
load_dotenv()
client = anthropic.Anthropic()
# Define the tools our agent can use
TOOLS = [
{
"name": "search_web",
"description": "Search the web for information on a topic. Returns a summary of top results.",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "The search query"}
},
"required": ["query"]
}
},
{
"name": "save_report",
"description": "Save the final research report to a markdown file.",
"input_schema": {
"type": "object",
"properties": {
"content": {"type": "string", "description": "The full report content in markdown"}
},
"required": ["content"]
}
}
]
defsearch_web(query: str) -> str:
"""Simulated web search — replace with real API in production."""# In production: integrate Tavily API (tavily.com) or SerpAPIreturnf"Search results for '{query}': [Simulated] Key findings include recent developments in {query}, major players in India, and practical applications for Indian users in 2026."defsave_report(content: str) -> str:
filename = f"report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"withopen(filename, 'w', encoding='utf-8') as f:
f.write(content)
returnf"Report saved to {filename}"defrun_agent(topic: str):
print(f"\n🤖 Starting research agent for: {topic}\n")
messages = [
{"role": "user", "content": f"Research the following topic and write a comprehensive structured report with sections, key insights, and actionable takeaways for Indian professionals: {topic}"}
]
whileTrue:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=4096,
tools=TOOLS,
messages=messages
)
# If Claude wants to use a toolif response.stop_reason == "tool_use":
tool_results = []
for block in response.content:
if block.type == "tool_use":
print(f" → Calling tool: {block.name}({json.dumps(block.input)[:60]}...)")
if block.name == "search_web":
result = search_web(**block.input)
elif block.name == "save_report":
result = save_report(**block.input)
else:
result = "Tool not found"
tool_results.append({"type": "tool_result", "tool_use_id": block.id, "content": result})
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
# If Claude is doneelif response.stop_reason == "end_turn":
final_text = next((b.text for b in response.content ifhasattr(b, 'text')), "")
print("\n✅ Agent complete!")
if final_text:
print("\n" + final_text[:500] + "...")
breakif __name__ == "__main__":
topic = input("Enter research topic: ")
run_agent(topic)
Replacing the Simulated Search
For a production-grade agent, replace the search_web function with a real API. Tavily AI (tavily.com) offers a search API with 1,000 free requests/month — perfect for Indian developers. Sign up, get an API key, and install with: pip install tavily-python
Step 6: Run and Test Your Agent
With the agent code saved, run it from your terminal. You will see the agent printing each tool call as it works through the research task. The agent may make 2–4 tool calls before producing the final report. Watch the output carefully — understanding when and why Claude chooses to call which tool is fundamental to improving your prompt and tool definitions. Try different topics: 'best programming languages to learn in India 2026', 'how Indian startups are using generative AI', 'top freelancing niches for Indian developers'.
bash
python agent.py
# Output:# Enter research topic: AI tools for Indian students 2026# # 🤖 Starting research agent for: AI tools for Indian students 2026# # → Calling tool: search_web({"query": "best AI tools Indian students 2026"})...# → Calling tool: search_web({"query": "free AI tools education India"})...# → Calling tool: save_report({"content": "# AI Tools for Indian Students..."})...# # ✅ Agent complete!# Report saved to report_20260608_143022.md
Step 7: Deploy for Free on Railway or Render
To run your agent on a schedule or make it accessible via a web endpoint, you can deploy it for free on Railway.app or Render.com. Both platforms have generous free tiers suitable for personal agents and small projects. The deployment process involves pushing your code to GitHub and connecting the repository to the hosting platform. Add your ANTHROPIC_API_KEY as an environment variable in the platform's dashboard, and your agent will run in the cloud without needing your laptop.
✓Push your code to a private GitHub repository
✓Sign up on Railway.app or Render.com (both free)
✓Connect your GitHub repo to the platform
✓Set ANTHROPIC_API_KEY as an environment variable
✓Deploy — your agent is now live in the cloud
How much does the Claude API cost for a personal agent?
The Claude API has a free tier suitable for development and light use. For production agents running dozens of requests per day, costs are approximately ₹0.50–₹2 per 1,000 tokens (roughly 750 words). A typical research report generation costs less than ₹2. Anthropic charges in USD — use a Niyo Global or Scapia virtual card for hassle-free international payments.
Can I build an agent that works with WhatsApp?
Yes. Integrate the WhatsApp Business API (via providers like Twilio or Gupshup) with your Claude agent backend. When a user sends a WhatsApp message, it triggers your agent, which processes the request and replies. This is how many Indian customer service bots are built. Meta's official WhatsApp Business API has a free tier for low-volume testing.
What is the difference between this and using ChatGPT plugins?
ChatGPT plugins are pre-built integrations you activate in the UI. Building your own agent gives you complete control — you define the tools, the logic, the data sources, and the output format. Custom agents are more flexible, can integrate with Indian-specific services, and can be deployed in your own infrastructure for data privacy.
Is Python the only language I can use?
No. Anthropic provides official SDKs for Python and TypeScript/JavaScript. There are community SDKs for Java, Go, and other languages. The REST API can be called from any language that supports HTTP requests, making it possible to build agents in virtually any tech stack.
Extend Your Agent with Real Web Search
Integrate the Tavily search API for live web results — our follow-up guide shows you how in 10 minutes.