Skip to main content
AG2 (formerly AutoGen) is an open-source framework for building and orchestrating AI agents. It focuses on enabling multiple agents to cooperate in solving complex tasks. The framework supports various language models from Toge, tool integrations, and both autonomous and human-in-the-loop workflows.

Installing Libraries

pip install autogen
Set your Neosantara AI API key:
export NAI_API_KEY=***

Example

Setup and configure AutoGen to use LLMs from Neosantara AI
import os

config_list = [
    {
        # Let's choose the Nusantara-Base model
        "model": "nusantara-base",
        "base_url": "https://api.neosantara.xyz/v1",
        # Provide your Neosantara.xyz API key here or put it into the NAI_API_KEY environment variable.
        "api_key": os.environ.get("NAI_API_KEY"),
        # We specify the API Type as 'openai' so it uses the OpenAI client class
        "api_type": "openai",
        "stream": False,
        "price": [300/1000000*1000, 1500/1000000*1000] # Input: $300/M tokens = $0.3/k tokens, Output: $1500/M tokens = $1.5/k tokens
    }
]
Importantly, we have tweaked the system message so that the model doesn’t return the termination keyword, which we’ve changed to FINISH, with the code block.
from pathlib import Path
from autogen import AssistantAgent, UserProxyAgent
from autogen.coding import LocalCommandLineCodeExecutor

# Setting up the code executor
workdir = Path("coding")
workdir.mkdir(exist_ok=True)
code_executor = LocalCommandLineCodeExecutor(work_dir=workdir)

# Setting up the agents

# The UserProxyAgent will execute the code that the AssistantAgent provides
user_proxy_agent = UserProxyAgent(
    name="User",
    code_execution_config={"executor": code_executor},
    is_termination_msg=lambda msg: "FINISH" in msg.get("content"),
)

system_message = """You are a helpful AI assistant who writes code and the user executes it.
Solve tasks using your coding and language skills.
In the following cases, suggest python code (in a python coding block) for the user to execute.
Solve the task step by step if you need to. If a plan is not provided, explain your plan first. Be clear which step uses code, and which step uses your language skill.
When using code, you must indicate the script type in the code block. The user cannot provide any other feedback or perform any other action beyond executing the code you suggest. The user can't modify your code. So do not suggest incomplete code which requires users to modify. Don't use a code block if it's not intended to be executed by the user.
Don't include multiple code blocks in one response. Do not ask users to copy and paste the result. Instead, use 'print' function for the output when relevant. Check the execution result returned by the user.
If the result indicates there is an error, fix the error and output the code again. Suggest the full code instead of partial code or code changes. If the error can't be fixed or if the task is not solved even after the code is executed successfully, analyze the problem, revisit your assumption, collect additional info you need, and think of a different approach to try.
When you find an answer, verify the answer carefully. Include verifiable evidence in your response if possible.
IMPORTANT: Wait for the user to execute your code and then you can reply with the word "FINISH". DO NOT OUTPUT "FINISH" after your code block."""

# The AssistantAgent, using Neosantara's nusantara-base model, will take the coding request and return code
assistant_agent = AssistantAgent(
    name="Neosantara-Assistant",
    system_message=system_message,
    llm_config={"config_list": config_list},
)

# Start the chat, with the UserProxyAgent asking the AssistantAgent the message
chat_result = user_proxy_agent.initiate_chat(
    assistant_agent,
    message="Provide code to count the number of prime numbers from 1 to 10000.",
)
User (to Neosantara-Assistant):

Provide code to count the number of prime numbers from 1 to 10000.

--------------------------------------------------------------------------------
Neosantara-Assistant (to User):

Berikut adalah rencana untuk menghitung jumlah bilangan prima dari 1 hingga 10000:
1.  Buat fungsi `is_prime` untuk memeriksa apakah suatu angka adalah bilangan prima.
2.  Iterasi dari 1 hingga 10000.
3.  Untuk setiap angka, gunakan fungsi `is_prime` untuk menentukan apakah angka tersebut prima.
4.  Jika angka tersebut prima, tambahkan ke penghitung.
5.  Cetak total penghitung setelah iterasi selesai.

```python
# script.py
def is_prime(n):
    """
    Checks if a number is prime.
    A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
    """
    if n <= 1:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    i = 3
    while i * i <= n:
        if n % i == 0:
            return False
        i += 2
    return True

count = 0
for number in range(1, 10001):
    if is_prime(number):
        count += 1

print(f"Jumlah bilangan prima dari 1 hingga 10000 adalah: {count}")
```

--------------------------------------------------------------------------------
Replying as User. Provide feedback to Neosantara-Assistant. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: explain it
User (to Neosantara-Assistant):

explain it

--------------------------------------------------------------------------------
Neosantara-Assistant (to User):

Kode yang diberikan bertujuan untuk menghitung jumlah bilangan prima dalam rentang 1 hingga 10000. Berikut adalah penjelasannya:

1.  **Fungsi `is_prime(n)`**:
    *   Fungsi ini dirancang untuk memeriksa apakah sebuah angka `n` adalah bilangan prima.
    *   **`if n <= 1: return False`**: Bilangan prima harus lebih besar dari 1. Jadi, angka 1 atau kurang dari 1 bukan prima.
    *   **`if n == 2: return True`**: Angka 2 adalah bilangan prima terkecil dan satu-satunya bilangan prima genap.
    *   **`if n % 2 == 0: return False`**: Setelah menangani angka 2, semua bilangan genap lainnya (yang lebih besar dari 2) tidak bisa menjadi prima karena mereka pasti habis dibagi 2.
    *   **`i = 3` dan `while i * i <= n:`**: Ini adalah bagian inti dari pemeriksaan. Kita memulai dengan pembagi `i = 3`. Kita hanya perlu memeriksa pembagi hingga akar kuadrat dari `n`. Jika `n` memiliki pembagi `p` yang lebih besar dari `sqrt(n)`, maka `n` juga harus memiliki pembagi `q = n/p` yang lebih kecil dari `sqrt(n)`. Dengan demikian, kita cukup memeriksa hingga `sqrt(n)`.
    *   **`if n % i == 0: return False`**: Jika `n` habis dibagi `i`, berarti `n` memiliki pembagi selain 1 dan dirinya sendiri, sehingga bukan prima.
    *   **`i += 2`**: Kita hanya perlu memeriksa pembagi ganjil, karena semua pembagi genap sudah ditangani atau tidak relevan (jika `n` sendiri ganjil). Jadi, `i` ditingkatkan sebesar 2.
    *   **`return True`**: Jika loop selesai tanpa menemukan pembagi, berarti `n` adalah bilangan prima.

2.  **Inisialisasi Penghitung**:
    *   `count = 0` : Sebuah variabel `count` diinisialisasi ke nol untuk menyimpan jumlah total bilangan prima yang ditemukan.

3.  **Loop Utama**:
    *   `for number in range(1, 10001):` : Loop ini mengiterasi setiap angka mulai dari 1 hingga 10000 (inklusif).
    *   `if is_prime(number):` : Untuk setiap `number` dalam iterasi, fungsi `is_prime()` dipanggil untuk memeriksa apakah angka tersebut prima.
    *   `count += 1` : Jika `is_prime()` mengembalikan `True`, berarti angka tersebut prima, dan `count` ditingkatkan satu.

4.  **Cetak Hasil**:
    *   `print(f"Jumlah bilangan prima dari 1 hingga 10000 adalah: {count}")` : Setelah loop selesai memproses semua angka dari 1 hingga 10000, nilai akhir dari `count` dicetak, menunjukkan total bilangan prima yang ditemukan.

--------------------------------------------------------------------------------