Creating Simple AI Agents: A Beginner's Guide
In today's rapidly evolving tech landscape, AI agents are becoming increasingly accessible to developers of all skill levels. This article introduces the concept of AI agents and walks through creating a simple yet practical example: a landing page generator powered by language models running locally on your system using Ollama.
What Are AI Agents?
AI agents are software programs that can perform tasks with varying degrees of autonomy using artificial intelligence techniques. They typically:
- Take input from users or environment
- Process information using AI models
- Perform actions based on this processing
- Provide output or feedback to users
The complexity of AI agents ranges from simple task-specific tools to sophisticated systems with complex reasoning capabilities.
Prerequisites: Running Local LLMs with Ollama
Before diving into our AI agent, make sure you have Ollama set up on your system. If you haven't installed it yet, I've written a comprehensive guide on how to run local LLMs with Ollama. This will walk you through the installation process and get you ready to build your first AI agent.
Anatomy of a Simple AI Agent
The landing page generator we're examining represents a basic AI agent with these key components:
1. User Interface
A command-line interface collecting user requirements and displaying results.
2. AI Integration Layer
Code that formats prompts and communicates with the AI model (Ollama's DeepSeek in this case).
3. Processing Logic
Functions for extracting relevant content from AI responses and saving the output.
4. Action Execution
Code that opens the generated landing page and handles user workflow.
How This Landing Page Generator Works
This agent follows a straightforward workflow:
- User Input: Collects a description of the desired landing page
- AI Instruction: Sends carefully crafted prompts to the language model
- Response Processing: Extracts HTML/CSS code from the model's response
- Output Generation: Saves the code as an HTML file
- Result Delivery: Opens the file in a browser and offers to create another
Key Design Principles
Looking at the code, we can identify several principles for effective AI agent design:
Clear, Specific Prompts
The system prompt defines the agent's role as a "skilled web developer" and provides specific constraints (using Tailwind CSS, delivering ready-to-use code).
Error Handling
The code gracefully handles potential failures in AI generation, extraction, and file operations.
User Experience Focus
The interface includes progress updates, confirmation prompts, and clear navigation options.
The Landing Page Generator Code
import ollama
import os
import re
from pathlib import Path
from datetime import datetime
def generate_landing_page(description):
"""Use Ollama to generate HTML with Tailwind CSS for a landing page based on description."""
messages = [
{"role": "system",
"content": "You are a skilled web developer who creates clean, responsive landing pages using HTML and Tailwind CSS. Your code should be complete, valid, and ready to use with just the Tailwind CDN."},
{"role": "user",
"content": f"Create a complete landing page based on this description: {description}. Use Tailwind CSS for styling (include the CDN link). Provide only the HTML code with Tailwind classes and minimal internal JavaScript if needed. The code should be complete and ready to be saved as an index.html file."}
]
try:
print("Generating landing page with Tailwind CSS... This may take a minute or two...")
response = ollama.chat(
model='deepseek-r1:8b',
messages=messages
)
# Extract HTML code from response
html_content = response['message']['content']
# Extract code between ```html and ``` if present
code_pattern = re.compile(r'```(?:html)?\s*([\s\S]*?)\s*```')
match = code_pattern.search(html_content)
if match:
return match.group(1).strip()
else:
# If no code blocks found, try to extract just the HTML
if "<html" in html_content and "</html>" in html_content:
start = html_content.find("<html")
end = html_content.find("</html>") + 7
return html_content[start:end]
return html_content
except Exception as e:
return f"Error generating landing page: {str(e)}"
def save_landing_page(html_content, output_dir="landing_pages"):
"""Save the generated HTML to a file."""
# Ensure the output directory exists
Path(output_dir).mkdir(exist_ok=True)
# Create a filename with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{output_dir}/landing_page_{timestamp}.html"
# Save the HTML content
with open(filename, "w", encoding="utf-8") as f:
f.write(html_content)
return filename
def main():
"""Run the dedicated landing page generator."""
print("==========================================")
print(" TAILWIND LANDING PAGE GENERATOR (OLLAMA) ")
print("==========================================")
# Get description for the landing page
print("\nDescribe the landing page you want (be specific about colors, layout, features):")
description = input("> ")
if not description:
print("Error: You must provide a description for the landing page.")
return
# Generate the landing page HTML
html_content = generate_landing_page(description)
# Save the landing page
filename = save_landing_page(html_content)
print(f"\nSuccess! Landing page created and saved to: {filename}")
# Ask if user wants to open the file
open_file = input("Would you like to open the landing page now? (y/n): ")
if open_file.lower() in ['y', 'yes']:
# Try to open the file in the default browser
try:
import webbrowser
file_path = os.path.abspath(filename)
webbrowser.open('file://' + file_path)
print(f"Opened {filename} in your default browser.")
except Exception as e:
print(f"Couldn't open the file automatically: {e}")
print(f"Please open {filename} manually in your browser.")
# Ask if user wants to create another landing page
another = input("\nWould you like to create another landing page? (y/n): ")
if another.lower() in ['y', 'yes']:
main() # Recursive call
else:
print("Thank you for using the Tailwind Landing Page Generator. Goodbye!")
if __name__ == "__main__":
main()
I am using deepseek-r1:8b and I have also tried qwen2.5-coder:14b which gave me a better result. Feel free to tweak the script to match your setup.
You can visit my GitHub Repo where I will be adding more examples as I continue my journey in this exciting field of AI.
Going Beyond: Enhancing Your AI Agents
Again, this is a simple example to help you get up and running with creating an AI Agent. To create more sophisticated AI agents, consider:
- Multiple Model Integration: Combine specialised models for different aspects of a task
- Memory and Context: Maintain conversation history for more coherent interactions
- User Preference Learning: Store and apply user preferences over time
- Feedback Loops: Collect user feedback to improve future outputs
- Validation Layers: Add code to validate AI outputs before presenting them
Conclusion
The landing page generator demonstrates how even simple AI agents can provide significant value. By combining clear prompts, effective processing, and thoughtful user experience design, developers can create tools that leverage AI to solve specific problems.
As you build your own AI agents, remember that the quality of your prompts, the robustness of your error handling, and the thoughtfulness of your user experience will largely determine your success.
In a nutshell, an AI agent is basically like calling an API with parameters, processing the result, manipulating it to your requirements and displaying the output. Anyone can get started with building an AI agent using Ollama or LM Studio. If you have a modest system, try using any of the smaller models such as qwen2.5-coder:3b or even a smaller model such as qwen2.5-coder:1.5b.
Smaller models are a great starting point, and while they may not offer the same quality as larger models, they are perfect for building your skills. As you get more comfortable with creating AI agents, you’ll be ready to work with larger models to unlock even more powerful capabilities!
Keep creating and innovating, and I would love to hear and see what you create. please feel free to share any comments, questions and examples of what you got done in the comments. If you need any help, feel free to reach out through my LinkedIn.
Member discussion