Functions & Classes

Classes & Objects

Classes and Objects

Classes help organize complex AI agent logic into reusable, maintainable structures.

Basic Class Structure

class ClassName:
    def __init__(self, params):
        self.attribute = params
    
    def method(self):
        return self.attribute

Key Concepts

  • `__init__` — Constructor, runs when creating instance
  • `self` — Reference to the instance
  • Attributes — Data stored in the instance
  • Methods — Functions that belong to the class

When to Use Classes for AI

  • Creating agent abstractions
  • Managing conversation state
  • Building tool collections
  • Handling API clients

Try It Yourself

Run this code example to practice what you've learned.

example.py
1from typing import Optional
2
3class AIAgent:
4 """A simple AI agent class."""
5
6 def __init__(self, name: str, model: str = "gpt-4"):
7 self.name = name
8 self.model = model
9 self.messages: list[dict] = []
10 self.tools: list[dict] = []
11
12 def add_system_message(self, content: str):
13 """Set the system prompt."""
14 self.messages.append({
15 "role": "system",
16 "content": content
17 })
18
19 def add_user_message(self, content: str):
20 """Add a user message to the conversation."""
21 self.messages.append({
22 "role": "user",
23 "content": content
24 })
25
26 def register_tool(self, name: str, description: str, func):
27 """Register a tool the agent can use."""
28 self.tools.append({
29 "name": name,
30 "description": description,
31 "function": func
32 })
33
34 def get_context(self) -> dict:
35 """Get the current agent context."""
36 return {
37 "agent": self.name,
38 "model": self.model,
39 "message_count": len(self.messages),
40 "tools": [t["name"] for t in self.tools]
41 }
42
43# Create and use the agent
44agent = AIAgent("ResearchBot", "gpt-4-turbo")
45agent.add_system_message("You are a helpful research assistant.")
46agent.add_user_message("Find information about Python.")
47
48# Register a tool
49def search(query: str) -> str:
50 return f"Results for: {query}"
51
52agent.register_tool("search", "Search the web", search)
53
54print("Agent Context:")
55for key, value in agent.get_context().items():
56 print(f" {key}: {value}")