---
title: "Cara Membangun AI Agent dari Nol dengan Python"
description: "Tutorial step-by-step membangun AI agent dengan Python. Pelajari function calling, tool execution, dan memory management untuk production-ready agent."
author: "Taufiq M"
author_url: https://devmode.id/taufiqm
url: https://devmode.id/taufiqm/ai-agent-dari-nol-python-raom
published: 2026-05-24T05:10:00.000Z
updated: 2026-05-24T05:10:00.000Z
language: id
tags: ["ai", "ai-agent", "python", "llm"]
publisher: "DEVMODE Community"
---

# Cara Membangun AI Agent dari Nol dengan Python

Oleh [Taufiq M](https://devmode.id/taufiqm) · 2026-05-24

AI agent sudah jadi bagian penting dari modern software stack. Tapi banyak developer yang stuck di level prompt engineering dan belum paham cara membangun agent yang reliable dari nol. Repository [ai-engineering-from-scratch](https://github.com/rohitg00/ai-engineering-from-scratch) oleh Rohit Ghumare menunjukkan bahwa membangun AI agent sebenarnya tidak serumit yang dibayangkan. Artikel ini akan membahas langkah praktis membangun AI agent dengan Python, mulai dari setup environment hingga deployment.

## Langkah 1: Setup Environment dan Dependency

Pastikan Python 3.10+ sudah terinstall. Buat virtual environment terpisah agar dependency tidak bentrok dengan project lain.

```
python -m venv venv
source venv/bin/activate
pip install openai python-dotenv requests
```

Buat file .env untuk menyimpan API key. Jangan hardcode secret ke dalam source code.

```
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxx
```

## Langkah 2: Bangun Core Agent dengan Function Calling

Agent yang baik bukan sekadar chatbot. Agent harus bisa memanggil function eksternal berdasarkan konteks percakapan. Berikut struktur dasar agent dengan OpenAI function calling:

```
import json
import os
from openai import OpenAI

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def get_weather(location: str):
    return {"location": location, "temperature": "28C", "condition": "cerah"}

functions = [{
    "name": "get_weather",
    "description": "Ambil data cuaca berdasarkan lokasi",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {"type": "string"}
        },
        "required": ["location"]
    }
}]

def run_agent(user_input):
    messages = [{"role": "user", "content": user_input}]
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
        functions=functions,
        function_call="auto"
    )
    return response.choices[0].message
```

## Langkah 3: Implementasikan Tool Execution Loop

Agent harus bisa mengeksekusi tool secara iteratif. Jika model merasa butuh data tambahan, ia akan memanggil function. Kita perlu loop untuk menangani multiple tool calls.

```
def agent_loop(user_input):
    messages = [{"role": "user", "content": user_input}]
    
    while True:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            functions=functions
        )
        msg = response.choices[0].message
        messages.append(msg)
        
        if msg.function_call:
            fn_name = msg.function_call.name
            args = json.loads(msg.function_call.arguments)
            result = globals()[fn_name](**args)
            messages.append({
                "role": "tool",
                "name": fn_name,
                "content": json.dumps(result)
            })
        else:
            return msg.content
```

## Langkah 4: Tambahkan Memory dengan Vector Store

Agent tanpa memory akan kehilangan konteks setiap sesi. Integrasikan vector store sederhana menggunakan ChromaDB atau bahkan in-memory dictionary untuk prototype.

```
memory = {}

def save_to_memory(key, value):
    memory[key] = value

def retrieve_memory(key):
    return memory.get(key, "Data tidak ditemukan")
```

Untuk production, gunakan ChromaDB, Pinecone, atau Weaviate dengan embedding model seperti text-embedding-3-small.

## Langkah 5: Deploy dengan FastAPI

Setelah agent berjalan lokal, expose via API menggunakan FastAPI. Ini memungkinkan integrasi dengan frontend atau service lain.

```
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Query(BaseModel):
    message: str

@app.post("/chat")
def chat(query: Query):
    return {"response": agent_loop(query.message)}
```

Jalankan dengan uvicorn main:app --reload dan test endpoint via curl atau Postman. Untuk production deploy, gunakan Docker dan platform seperti Railway atau Fly.io.

## Kesimpulan

Membangun AI agent dari nol membutuhkan pemahaman tentang function calling, tool execution, dan memory management. Dengan Python dan OpenAI API, kamu sudah bisa membuat agent production-ready dalam hitungan jam. Source code lengkap bisa dilihat di repository [ai-engineering-from-scratch](https://github.com/rohitg00/ai-engineering-from-scratch).

---

Sumber: https://devmode.id/taufiqm/ai-agent-dari-nol-python-raom (DEVMODE Community)
