Welcome! This is a simple, working example of an AI agent - think of it as a "Hello World" program for AI.
It is a program that:
- Listens to what you ask
- Decides what action to take
- Uses tools to get answers
- Explains what it did
Imagine a helpful assistant that doesn't just answer from memory - it can search the web, calculate numbers, and check the time.
pip install -r requirements.txtCreate a .env file in this folder:
GROQ_API_KEY=your_actual_key_here
Get a free key from: https://console.groq.com/keys
streamlit run single_agent_with_tools.pyOpen your browser to: http://localhost:8501
Type any question in the chat box:
You ask: "What are the latest developments in AI agents in 2026?"
Agent thinks: "I need current information → use web search"
↓
Searches the web
↓
Returns latest news
You ask: "Calculate 25% of 2000"
Agent thinks: "This is a math problem → use calculator"
↓
Calculates: 2000 * 0.25 = 500
↓
Returns the answer
You ask: "What's today's date?"
Agent thinks: "User wants date/time → use datetime tool"
↓
Gets current date
↓
Shows: Friday, April 04, 2026 at 03:45 PM
- Searches the internet in real-time
- No API key needed
- Returns relevant results
- Try: "Latest news about AI", "What is quantum computing?"
- Evaluates any math expression
- Supports:
+,-,*,/,%,**(power) - Handles complex expressions with parentheses
- Try: "2 + 2", "100 * 3.14", "(50 + 30) / 4"
- Gets current date and time
- Shows day of week
- Try: "What time is it?", "Today's date"
An agent evaluates three things when picking a tool:
| Component | What It Is | Why It Matters |
|---|---|---|
| Tool Name | Identifier (e.g., search_web) |
First signal, gives a hint about purpose |
| Description (Docstring) | What the tool does & when to use it | Most important, agent relies on this most heavily |
| Parameters | Input the tool needs (e.g., query: str) |
Confirms if the tool fits the current context |
💡 Key insight: The description is the most critical component. A poorly written docstring = agent picks the wrong tool, even if the tool itself is perfect.
┌─────────────────────────────────────────────┐
│ YOU ASK A QUESTION │
│ "Calculate 15% of 500" │
└──────────────┬──────────────────────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ AI AGENT READS YOUR QUESTION │
│ (Uses LLM) │
└──────────────┬──────────────────────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ AGENT DECIDES: WHICH TOOL FITS? │
│ → "This is math → use Calculator" │
└──────────────┬──────────────────────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ TOOL EXECUTES │
│ calculator("500 * 0.15") │
│ → Result: "500 * 0.15 = 75" │
└──────────────┬──────────────────────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ AGENT EXPLAINS ANSWER │
│ "15% of 500 is 75" │
│ (Shows: 🔧 calculator used) │
└──────────────┬──────────────────────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ YOU GET ANSWER + SEE WHAT TOOL WAS USED │
└─────────────────────────────────────────────┘
This pattern is called ReAct: Reasoning → Acting → Result
Lines 37-63 - Look for @tool decorator
@tool
def calculator(expression: str) -> str:
"""Tool description - tells agent when to use it"""
try:
result = evaluate(expression) # Safe math evaluation
return f"{expression} = {result}"
except Exception as e:
return f"Error calculating: {e}"Lines 70-75 - Creates the smart decision maker
agent = create_react_agent(
model=llm, # The AI brain (Llama)
tools=tools, # Available tools
prompt="..." # Instructions for agent
)Lines 81-87 - Remembers conversation
if "agent_messages" not in st.session_state:
st.session_state.agent_messages = [...]Try these to understand how the agent works:
Add a greeting tool:
@tool
def greet(name: str) -> str:
"""Greet a person by name."""
return f"Hello {name}! I'm an AI assistant. How can I help?"Then ask the agent: "Say hello to Alice"
Modify line 72 to make agent behave differently:
prompt="You are a sarcastic AI assistant. Use tools when needed."Try these to see tool selection in action:
- ❌ "What is 2+2?" → Agent uses calculator
- ✅ "Search Google for AI news" → Agent uses web search
- ⏰ "It's currently _____?" → Agent uses datetime
- Make sure
.envfile exists in the same folder - Check the API key is correct (no spaces!)
- Restart the app:
Ctrl+Cthenstreamlit run ...
- Try a simpler query
- Check your internet connection
- DuckDuckGo might be rate limiting - wait a minute
- Check your math expression syntax
- Use parentheses for complex formulas:
(10 + 5) * 2 - Avoid unsafe characters
| Package | Purpose |
|---|---|
langchain_groq |
Connect to Llama AI |
langchain_core |
Build tools and agents |
langgraph |
Agent framework (ReAct) |
duckduckgo_search |
Web search |
numexpr |
Safe math calculations |
streamlit |
Web interface |
- Never share your
.envfile - Don't put API keys in the code
- Don't expose this to untrusted users on a public server
After running this, you can:
- Add more tools - Try adding weather, stock prices, Wikipedia lookup
- Improve prompts - Make the agent more specialized
- Try different models - Switch to GPT-4, Claude, etc.
- Build memory - Make the agent remember across conversations
- Add persistence - Save conversations to a database
Q: Can I add more tools?
A: Yes! Just create a function with @tool decorator and add it to the tools list.
Q: Why Streamlit UI? A: It's the easiest way for beginners to see results without building a web app from scratch.
Q: Is this production-ready? A: No. It's for learning. For production, add: authentication, rate limiting, logging, error tracking.
Q: Why Llama model? A: It's fast, free via Groq, and good for learning. You can swap it for other models!
- LangChain Docs: https://python.langchain.com/
- LangGraph Docs: https://langchain-ai.github.io/langgraph/
- ReAct Paper: https://arxiv.org/abs/2210.03629
- Groq Console: https://console.groq.com/
- Start simple - Ask questions that clearly need a tool
- Read the output - Notice which tool was used and why
- Experiment - Change prompts, add tools, break things!
- Read the code - It's only ~150 lines, very readable
- Ask questions - Try weird queries to see how agent reacts
single_agent_with_tools.py
├── Imports (AI libraries)
├── Configuration (API keys, Streamlit setup)
├── Tool Definitions (3 functions with @tool)
├── Agent Creation (ReAct agent with tools)
├── Chat Interface (Streamlit UI)
└── Message Handling (conversation loop)
You now have a working AI agent. This is a real, functional intelligent system - the same patterns power production AI applications.
What you learned:
- ✅ How agents reason
- ✅ How to define tools
- ✅ How to let AI choose actions
- ✅ How to build interactive UIs
What's next:
- Make it cooler (more tools!)
- Make it smarter (better prompts)
- Make it useful (real-world tools)
Questions? Issues? Feel free to connect! Happy learning! 🚀