</>
Skip to content
Gen AI lessons (22/39)

Gen AI — AI Agents

What are AI agents?

Autonomous systems that use LLMs to plan, reason, and take actions.

Agent architecture

User → Agent → Plan → Execute → Observe → Repeat

Basic agent

import openai

client = openai.OpenAI()

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"}
                }
            }
        }
    }
]

response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Weather in NYC?"}],
    tools=tools
)

Tool execution

import json

def execute_tool(tool_call):
    if tool_call.function.name == "get_weather":
        args = json.loads(tool_call.function.arguments)
        return get_weather(args["location"])

# Process tool calls
for tool_call in response.choices[0].message.tool_calls:
    result = execute_tool(tool_call)
    
    # Feed result back to model
    messages.append({"role": "tool", "content": str(result)})

Agent loop

def agent_loop(user_message):
    messages = [{"role": "user", "content": user_message}]
    
    while True:
        response = client.chat.completions.create(
            model="gpt-4",
            messages=messages,
            tools=tools
        )
        
        if response.choices[0].message.tool_calls:
            # Execute tools and continue
            for tool_call in response.choices[0].message.tool_calls:
                result = execute_tool(tool_call)
                messages.append({"role": "tool", "content": str(result)})
        else:
            # No more tool calls, return final answer
            return response.choices[0].message.content

Mini Practice

  1. Create a simple agent
  2. Add multiple tools
  3. Implement agent loop
  4. Test with complex queries

Up Next

Continue with Function Calling - Connecting to APIs.

Related Topics

Frequently Asked Questions about AI Agents

What is AI Agents in Gen AI?

AI Agents is a fundamental concept in Gen AI. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn AI Agents?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn AI Agents.

Why is AI Agents important in Gen AI?

AI Agents is essential for Gen AI development. Understanding this concept will help you write better code and solve real-world problems more effectively.