Learn to Build an Intelligent System from the Ground Up
Medium Link: https://generativeai.pub/building-an-ai-agent-from-scratch-a-step-by-step-guide-cf1a356d6125
AI agents are changing the way we interact with technology. These smart beings are able to sense their environment, make decisions, and take actions in a bid to achieve some goals. We will learn how to create an AI agent from scratch with Python, building a simple yet functional agent that can make decisions and take action.
An AI agent is an independent system that interacts with the environment in a way to complete specific tasks. Agents can vary from as simple as reactive systems to as complex as learning, adaptive beings. Common AI agents are:
Reactive Agents: React immediately to stimuli without remembering previous experience.
Model-Based Agents: They make appropriate decisions based on their internal models.
Goal-Based Agents: Plan and act in pursuit of pre-stated goals.
Utility-Based Agents: They select actions for achieving the best outcome depending on a utility function.
Real-Life Examples
AI agents are employed in different applications such as chatbots, recommendation systems, autonomous vehicles, and intelligent assistants.
An AI agent consists of four fundamental components:
Model: The “brain” which takes in inputs and produces answers.
Tools are instruments through which the agent can act.
Toolbox: Set of easily accessible tools.
System Prompt: Directives that control the agent’s actions.
Source: technexus
Before building the AI agent, ensure that Python (version 3.8 or later) is installed. Set up a virtual environment for dependency management:
python -m venv ai_agent_env
source ai_agent_env/bin/activate # On Windows: ai_agent_env\Scripts\activate
pip install requests termcolor python-dotenv
The model class is responsible for processing user input and generating responses. The following class integrates with a local API to retrieve responses:
from termcolor import colored
import requests
import json
import os
from dotenv import load_dotenv
load_dotenv()
class OllamaModel:
def __init__(self, model, system_prompt, temperature=0):
self.model_endpoint = "http://localhost:11434/api/generate"
self.model = model
self.system_prompt = system_prompt
self.temperature = temperature
def generate_text(self, prompt):
payload = {
"model": self.model,
"prompt": prompt,
"system": self.system_prompt,
"temperature": self.temperature
}
response = requests.post(self.model_endpoint, json=payload)
return response.json()
Define simple functions that execute specific tasks. Below are two basic tools:
def basic_calculator(input_data):
"""Perform arithmetic operations."""
num1, num2, operation = input_data['num1'], input_data['num2'], input_data['operation']
operations = {'add': num1 + num2, 'subtract': num1 - num2}
return operations.get(operation, "Invalid operation")
def reverse_string(input_string):
"""Reverse the given string."""
return input_string[::-1]
The toolbox organizes the available tools:
class ToolBox:
def __init__(self):
self.tools_dict = {}
def store(self, tools):
for tool in tools:
self.tools_dict[tool.__name__] = tool.__doc__
def list_tools(self):
return "\n".join([f"{name}: {desc}" for name, desc in self.tools_dict.items()])
The AI agent determines which tool to use and executes it based on input:
class Agent:
def __init__(self, tools, model_service):
self.tools = tools
self.model_service = model_service
def think(self, prompt):
tool_descriptions = ToolBox().list_tools()
system_prompt = f"Tools available:\n{tool_descriptions}"
response = self.model_service.generate_text(prompt)
return response
def act(self, prompt):
response = self.think(prompt)
tool_name = response.get("tool_choice")
tool_input = response.get("tool_input")
for tool in self.tools:
if tool.__name__ == tool_name:
return tool(tool_input)
Source: researchgate.net
Integrate all components and execute the AI agent:
if __name__ == "__main__":
tools = [basic_calculator, reverse_string]
model_service = OllamaModel(model="llama2", system_prompt="Your instructions here")
agent = Agent(tools=tools, model_service=model_service)
while True:
user_input = input("Ask me anything: ")
if user_input.lower() == "exit":
break
print(agent.act(user_input))
The first steps of building an AI agent in Python are covered in this tutorial. We can build intelligent systems with high performance by organizing an agent into models, tools, and prompts. Agents will play an increasingly important role in most fields as AI technology advances.
Key Points
In their environment, AI agents function autonomously.
A model, tools, a toolbox, and system prompts are essential elements.
Sensible decisions and actions can be made by a structured agent.
This deployment is just the start; machine learning techniques can be used in future upgrades to increase decision-making and flexibility even further.
Join Kalash on Peerlist!
Join amazing folks like Kalash and thousands of other people in tech.
Create ProfileJoin with Kalash’s personal invite link.
0
6
1