\n\n\n\n I Built an AI Agent From Scratch, Heres How Agent 101 \n

I Built an AI Agent From Scratch, Heres How

📖 10 min read1,849 wordsUpdated Mar 26, 2026

Hey there, agent-in-training! Emma here from agent101.net, and today we’re tackling a question that’s been buzzing in my DMs more than usual lately: “Okay, Emma, I get the hype, but how do I actually *build* one of these AI agents people keep talking about? Like, from scratch, without needing a PhD in computer science?”

Trust me, I’ve been there. Not too long ago, the idea of an AI agent felt like something out of a sci-fi movie – cool, futuristic, but utterly out of reach for a regular person like me who just wants to automate some annoying tasks or build something genuinely useful. But guess what? It’s not. The barrier to entry has dropped dramatically, and with a bit of guidance (and maybe a few late-night coffee sessions, if you’re like me), you can absolutely build your first AI agent. And that’s what we’re doing today.

Forget the generic overviews. We’re going to explore the practical nitty-gritty of building a specific type of AI agent: a simple, task-oriented agent that can interact with a web API to fetch information. Think of it as your personal data retriever, but with a brain (a small one, for now!). Specifically, we’re going to build an agent that can fetch the current weather for a given city using a free weather API. Why weather? Because it’s a common, easy-to-understand use case with readily available APIs, perfect for our beginner journey.

My First “Aha!” Moment with Agents

I remember my own ‘aha!’ moment. It wasn’t some grand project; it was trying to automate the process of finding out if my favorite coffee shop was open on a public holiday. Manually checking their website, then their Instagram, then their Google Maps listing felt like a monumental effort. I thought, “There *has* to be a better way.” That’s when I started tinkering with basic scripting and then, eventually, stumbled into the world of AI agents. The idea of an autonomous piece of software that could *understand* my intent (“Is Coffee Oasis open?”) and *act* on it (check multiple sources, synthesize the info, tell me the answer) was mind-blowing. It’s a fundamental shift from just writing a script to having a program that can reason and decide.

So, let’s replicate that feeling, even if our first agent is a bit simpler. We’re aiming for understanding the core components, not building Skynet.

What Do We Even Mean by “AI Agent” Here?

Before we jump into code, let’s clarify. When I talk about a “beginner AI agent,” I’m referring to a program that:

  • **Perceives:** It takes input (like your request, “What’s the weather in London?”).
  • **Thinks/Reasons (simply):** It processes that input to understand what needs to be done.
  • **Acts:** It performs an action based on its reasoning (like calling a weather API).
  • **Learns (optional for this beginner project, but important for future):** It might store or adapt based on past interactions.

For our weather agent, the “thinking” part will be basic: identifying the city name. The “acting” part will be making an API request. Simple, but effective!

The Tools We’ll Need (Don’t Panic, They’re Free!)

You don’t need fancy, expensive software. Here’s our minimal toolkit:

  • **Python:** Our programming language of choice. It’s beginner-friendly and has excellent libraries for everything we need. Make sure you have Python 3 installed.
  • **A text editor:** VS Code, Sublime Text, Atom, or even Notepad++ will do.
  • **Requests library:** A Python library for making HTTP requests (how we’ll talk to the weather API).
  • **A Free Weather API Key:** We’ll use OpenWeatherMap because it’s super easy to get started with.

Getting Your OpenWeatherMap API Key

This is crucial. Head over to OpenWeatherMap’s API page. You’ll need to create a free account. Once logged in, navigate to the “API keys” tab. You’ll see your default API key there. Copy it down; we’ll need it soon.

**Pro-tip:** API keys are like passwords. Don’t share them publicly! And for real projects, you’d store them in environment variables, not directly in your code. But for this beginner tutorial, putting it directly in the script for a moment is okay for learning, as long as you understand the security implications.

Step-by-Step: Building Our Weather Agent

Alright, let’s get our hands dirty!

1. Set Up Your Project

Create a new folder for your project, say `my_weather_agent`. Inside that folder, create a new Python file, like `weather_agent.py`.

Open your terminal or command prompt, navigate to your project folder, and install the `requests` library:

pip install requests

2. The Core Components: Functions!

Our agent will need a few key functions:

  • One to fetch the weather data from the API.
  • One to process the user’s input.
  • One to put it all together.

3. Writing the API Interaction Function

This function will take a city name and your API key, then make the request to OpenWeatherMap and return the raw data.


import requests

# --- IMPORTANT: Replace with your actual API key ---
API_KEY = "YOUR_OPENWEATHERMAP_API_KEY" 
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"

def get_weather_data(city_name):
 """
 Fetches raw weather data for a given city from OpenWeatherMap.
 """
 params = {
 "q": city_name,
 "appid": API_KEY,
 "units": "metric" # You can change to "imperial" for Fahrenheit
 }
 try:
 response = requests.get(BASE_URL, params=params)
 response.raise_for_status() # Raises an HTTPError for bad responses (4xx or 5xx)
 return response.json()
 except requests.exceptions.HTTPError as errh:
 print(f"HTTP Error: {errh}")
 return None
 except requests.exceptions.ConnectionError as errc:
 print(f"Error Connecting: {errc}")
 return None
 except requests.exceptions.Timeout as errt:
 print(f"Timeout Error: {errt}")
 return None
 except requests.exceptions.RequestException as err:
 print(f"An unexpected error occurred: {err}")
 return None

**Remember to replace `”YOUR_OPENWEATHERMAP_API_KEY”` with the actual key you copied!**

4. Processing and Displaying the Weather

The raw JSON data from the API can be a bit much. Let’s create a function to extract the useful bits and present them nicely.


def display_weather(weather_data):
 """
 Parses and displays relevant weather information.
 """
 if weather_data and weather_data.get("cod") == 200: # Check if the request was successful
 city = weather_data["name"]
 country = weather_data["sys"]["country"]
 temp = weather_data["main"]["temp"]
 feels_like = weather_data["main"]["feels_like"]
 description = weather_data["weather"][0]["description"]
 humidity = weather_data["main"]["humidity"]
 wind_speed = weather_data["wind"]["speed"]

 print(f"\n--- Weather in {city}, {country} ---")
 print(f"Temperature: {temp}°C (feels like {feels_like}°C)")
 print(f"Conditions: {description.capitalize()}")
 print(f"Humidity: {humidity}%")
 print(f"Wind Speed: {wind_speed} m/s")
 print("-------------------------------\n")
 elif weather_data and weather_data.get("cod") == "404":
 print(f"Sorry, couldn't find weather for that city. Please check the spelling.")
 else:
 print("Could not retrieve weather information. Please try again later.")

5. The Agent’s “Brain” – Putting It All Together

This is where our simple agent loop comes in. It will prompt the user, call our functions, and keep going until the user decides to quit.


def run_weather_agent():
 """
 Main loop for our simple weather agent.
 """
 print("Welcome to your simple Weather Agent!")
 print("Type 'quit' or 'exit' to stop at any time.")

 while True:
 user_input = input("Enter a city name to get the weather: ").strip()

 if user_input.lower() in ["quit", "exit"]:
 print("Goodbye! Stay weather-aware!")
 break

 if not user_input:
 print("Please enter a city name.")
 continue

 print(f"Fetching weather for {user_input}...")
 weather_data = get_weather_data(user_input)
 display_weather(weather_data)

6. Running Your Agent!

Finally, we need to call our `run_weather_agent()` function to kick things off. Add this line at the very end of your `weather_agent.py` file:


if __name__ == "__main__":
 run_weather_agent()

Now, save your file and run it from your terminal:

python weather_agent.py

You should see a prompt asking for a city name! Try “London”, “Tokyo”, “New York”, or even a typo to see the error handling. This is it – your first AI agent, performing a task autonomously!

Beyond the Basics: How This Connects to More Complex Agents

You might be thinking, “Okay, Emma, this is cool, but it’s not exactly Jarvis, is it?” And you’d be right! But this simple weather agent demonstrates the fundamental loop that even the most complex AI agents follow:

  • **Perception:** Our agent perceives your input (the city name). In more advanced agents, this could be interpreting natural language, reading data from sensors, or analyzing vast datasets.
  • **Reasoning/Planning:** Our agent’s “reasoning” is simple: “If I get a city name, call the weather API.” More complex agents use sophisticated models (like large language models – LLMs) to understand intent, break down complex tasks into sub-tasks, and choose appropriate tools.
  • **Action:** Our agent’s action is making an HTTP request to an API. Advanced agents might interact with databases, send emails, control robots, or generate creative content.
  • **Feedback/Learning (Implicit here):** If the city name is wrong, our `display_weather` function gives feedback. In advanced agents, this feedback loop is explicit, allowing the agent to refine its strategies or learn new skills over time.

My own journey started with these small, functional scripts. It was only after understanding how to connect these building blocks that I could start envisioning more ambitious projects. This weather agent is your first step on that path!

Actionable Takeaways for Your Agent Journey

So, you’ve built your first agent. What’s next?

  1. **Experiment!** Change the `units` parameter in `get_weather_data` to “imperial”. Add more weather details to the display. What happens if you try to get weather for a non-existent city?
  2. **Explore Other APIs:** The web is full of free APIs! Think about a simple agent that fetches movie information from OMDB, news headlines from NewsAPI, or even dad jokes from a joke API. Each new API is a new “tool” your agent can learn to use.
  3. **Think About Intent:** Our agent only understands “city name.” How would you modify it to understand something like “What’s the weather like for my trip to Paris next week?” This is where parsing natural language and integrating with an LLM comes in – a big leap, but one you can start to conceptualize now.
  4. **Error Handling is Your Friend:** Notice all those `try…except` blocks? They’re vital. Real-world systems fail, and a good agent anticipates those failures and handles them gracefully.
  5. **Don’t Be Afraid to Break Things:** Seriously, that’s how you learn. Change something, see what happens, fix it. Rinse and repeat.

Building AI agents might seem daunting at first, but by starting with practical, small projects like this weather agent, you’re laying a solid foundation. You’re learning the fundamental cycle of perceive-reason-act that underpins all intelligent systems. And trust me, once you get that first agent working, you’ll start seeing possibilities everywhere. Happy agent building!

🕒 Last updated:  ·  Originally published: March 13, 2026

🎓
Written by Jake Chen

AI educator passionate about making complex agent technology accessible. Created online courses reaching 10,000+ students.

Learn more →

Leave a Comment

Your email address will not be published. Required fields are marked *

Browse Topics: Beginner Guides | Explainers | Guides | Opinion | Safety & Ethics

More AI Agent Resources

BotclawAgnthqAgntapiAgntdev
Scroll to Top