Introduction
AutoGPT is a pure Rust framework that makes building, deploying, and orchestrating intelligent AI agents as natural as writing idiomatic Rust code. It solves the hard problems of agentic AI so you can focus on what your agents actually do.
What Problem Does AutoGPT Solve?
Building production-grade AI agents is painful. You need to wire up LLM API calls, manage conversation state, handle retries, persist long-term memory, coordinate multiple agents, secure inter-agent communication, and integrate version control, all before writing any business logic.
AutoGPT eliminates this boilerplate. Define a persona and a behavior. The framework handles everything else.
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let agent = ArchitectGPT::new(
"Lead UX/UI Designer",
"Generate a Kubernetes architecture diagram with Prometheus monitoring.",
).await;
AutoGPT::default()
.with(agents![agent])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
That is the entire program. AutoGPT initializes the LLM client, constructs the task, runs the agent asynchronously, and writes the output to the workspace.
Core Capabilities
Blazing Speed
Written entirely in safe Rust with async/await and Tokio. Agents run concurrently with zero-cost abstractions.
Composable Agents
Mix built-in agents or bring your own via the Auto derive macro and Executor trait.
Multi-Provider LLMs
Gemini, OpenAI, Anthropic Claude, XAI Grok, Cohere, and HuggingFace, switch with a single env var.
Secure Networking
IAC protocol over QUIC/TLS with Ed25519 cryptographic agent identity for distributed deployments.
Long-Term Memory
Pinecone vector database integration to persist and recall agent knowledge across sessions.
9 Built-in Agents
ManagerGPT, ArchitectGPT, BackendGPT, FrontendGPT, DesignerGPT, GitGPT, MailerGPT, OptimizerGPT, and GenericGPT.
Collaborative Agents
Route tasks across multiple LLM providers with CollabPool. Automatic model-level fallback on quota/rate-limit errors.
Metacognition
Agents record task outcomes and inject strategy context into prompts. Self-corrects strategy after consecutive failures.
Architecture at a Glance
flowchart TD
User(["π€ User"])
subgraph Runtime["AutoGPT Runtime"]
direction TB
MG["π© ManagerGPT"]
AG["π· ArchitectGPT"]
BG["βοΈ BackendGPT"]
FG["π₯οΈ FrontendGPT"]
DG["π¨ DesignerGPT"]
end
subgraph Network["Orchestrated Mode (IAC / TLS)"]
direction LR
Orch["π orchgpt Orchestrator"]
end
subgraph Providers["LLM Providers"]
Gemini["Gemini"]
OpenAI["OpenAI"]
Claude["Claude"]
XAI["XAI"]
HF["HuggingFace"]
end
DB[("π§ Pinecone Vector DB")]
User -->|"goal prompt"| MG
MG --> AG
MG --> BG
MG --> FG
MG --> DG
User -->|"--net"| Orch
Orch <-->|"IAC + Ed25519"| MG
Runtime <-->|"API calls"| Providers
Runtime <-->|"save_ltm / get_ltm"| DB
Operating Modes
| Mode | Command | Description |
|---|---|---|
| Interactive Shell | autogpt | Conversational AI shell with session management |
| Direct Prompt | autogpt -p "..." | One-shot LLM query from the terminal |
| Standalone Agent | autogpt arch / back / front | Run a single specialized agent |
| Orchestrated | autogpt --net | Networked multi-agent mode via IAC/TLS |
| Collaborative | autogpt --collab | Round-robin multi-provider collab mode |
Quick Links
- Installation β: Get AutoGPT running in minutes.
- Quickstart β: Build your first agent.
- Custom Agents β: Compose your own agent from scratch.
- Collaborative Agents β: Route tasks across multiple LLM providers.
- Metacognition β: Self-correcting strategy via recorded outcomes.
- IAC Protocol β: Understand the communication layer.
- GitHub: Source code and releases.
0.x API is stabilizing. For the latest changes, follow the GitHub releases.
Installation
AutoGPT ships as two binaries in a single crate: autogpt (the agent runner) and orchgpt (the orchestrator). Choose your preferred installation method below.
From crates.io
The fastest way to install both binaries:
cargo install autogpt --all-features
After installation, verify both binaries are available:
autogpt --version
orchgpt --version
Pre-built Binaries
Download the latest pre-built executables directly from GitHub Releases without a Rust toolchain:
| Platform | Download |
|---|---|
| Linux x86-64 | autogpt |
| Windows x86-64 | autogpt.exe |
Using Docker
Run AutoGPT inside an isolated container, no Rust installation required.
AutoGPT agent container:
docker run -it \
-e GEMINI_API_KEY=<your_gemini_api_key> \
-e PINECONE_API_KEY=<your_pinecone_api_key> \
-e PINECONE_INDEX_URL=<your_pinecone_index_url> \
--rm --name autogpt kevinrsdev/autogpt
OrchGPT orchestrator container:
docker run -it \
-e GEMINI_API_KEY=<your_gemini_api_key> \
-e PINECONE_API_KEY=<your_pinecone_api_key> \
-e PINECONE_INDEX_URL=<your_pinecone_index_url> \
--rm --name orchgpt kevinrsdev/orchgpt
Build from Source
Building from source gives you access to all development features and the latest unreleased code.
1. Clone the repository:
git clone https://github.com/wiseaidotdev/autogpt.git
cd autogpt/autogpt
2. Build and run the agent CLI:
cargo run --all-features --bin autogpt
3. Build and run the orchestrator:
cargo run --all-features --bin orchgpt
4. Or build an optimized release binary:
cargo build --release --all-features
# Binaries land in: ./target/release/autogpt and ./target/release/orchgpt
SDK Installation
To embed AutoGPT in your own Rust project, add it to your Cargo.toml:
[dependencies]
autogpt = { version = "0.4.5", features = ["gem", "gpt"] }
tokio = { version = "1", features = ["full"] }
Select only the feature flags you need to minimize compile times and binary size.
rustup update stable to ensure you have a compatible toolchain.
Configuration
AutoGPT is configured entirely through environment variables, no config files required. The table below lists every variable with its purpose, whether it is required, and which feature flag it belongs to.
Core Variables
| Variable | Required | Default | Description |
|---|---|---|---|
AI_PROVIDER | No | gemini | Active LLM provider: gemini, openai, anthropic, xai, cohere, huggingface |
AUTOGPT_WORKSPACE | No | . (cwd) | Workspace root where agents write generated files |
ORCHESTRATOR_ADDRESS | CLI only | 0.0.0.0:8443 | TCP address the orchestrator listens on |
LLM Provider API Keys
Configure the key for your chosen provider. Only the key matching your AI_PROVIDER value is required.
# Gemini (default), requires feature: gem
export AI_PROVIDER=gemini
export GEMINI_API_KEY=<your_gemini_api_key>
# Override the Gemini model (otherwise uses first in provider list)
export GEMINI_MODEL=gemini-2.5-pro-preview-05-06
# OpenAI, requires feature: oai
export AI_PROVIDER=openai
export OPENAI_API_KEY=<your_openai_api_key>
export OPENAI_MODEL=gpt-4o # optional override
# Anthropic Claude, requires feature: cld
export AI_PROVIDER=anthropic
export ANTHROPIC_API_KEY=<your_anthropic_api_key>
export ANTHROPIC_MODEL=claude-opus-4-6 # optional override
# XAI Grok, requires feature: xai
export AI_PROVIDER=xai
export XAI_API_KEY=<your_xai_api_key>
export XAI_MODEL=grok-4 # optional override
# Cohere, requires feature: co
export AI_PROVIDER=cohere
export COHERE_API_KEY=<your_cohere_api_key>
export COHERE_MODEL=command-r-plus # optional override
# HuggingFace, requires feature: hf
export AI_PROVIDER=huggingface
export HF_API_KEY=<your_hf_api_key>
export HF_MODEL=meta-llama/Llama-3.3-70B-Instruct # optional override
Obtain a Gemini API key from Google AI Studio. Keys for other providers are available on their respective developer portals.
Workspace
GenericGPT defaults to the current directory where the CLI is launched as its workspace. Set AUTOGPT_WORKSPACE to override:
export AUTOGPT_WORKSPACE=/my/project
autogpt # file operations are scoped to /my/project
For the classic multi-agent workflow (BackendGPT, FrontendGPT, etc.), all agents write to subdirectories:
workspace/
βββ architect/ # ArchitectGPT: diagram.py and generated PNGs
βββ backend/ # BackendGPT: main.py, template.py, etc.
βββ frontend/ # FrontendGPT: HTML/CSS/JS files
βββ designer/ # DesignerGPT: image assets
The .autogpt Directory
GenericGPT maintains persistent state in a hidden directory inside the active workspace:
.autogpt/
βββ sessions/ # Markdown conversation snapshots, auto-saved after every response
β βββ <uuid>.md
β βββ ...
βββ skills/ # Learned lessons, injected on future sessions (TOML)
βββ rust.toml
βββ web.toml
βββ python.toml
Lesson files are plain TOML and can be viewed or manually edited. See the GenericGPT agent documentation for details.
Orchestrator Address
When running in Orchestrated Mode, the orchestrator (orchgpt) needs a bind address and the agent (autogpt --net) needs to know where to connect:
# On the orchestrator host
export ORCHESTRATOR_ADDRESS=0.0.0.0:8443
# On the agent host (must point to the orchestrator)
export ORCHESTRATOR_ADDRESS=192.168.1.10:8443
Optional: DesignerGPT (img)
Enables AI-generated image creation via GetImg:
export GETIMG_API_KEY=<your_getimg_api_key>
Optional: MailerGPT (mail)
Enables email reading and sending via Nylas:
export NYLAS_SYSTEM_TOKEN=<your_nylas_system_token>
export NYLAS_CLIENT_ID=<your_nylas_client_id>
export NYLAS_CLIENT_SECRET=<your_nylas_client_secret>
Optional: Long-Term Memory (mem)
Persists agent memory in Pinecone vector database:
export PINECONE_API_KEY=<your_pinecone_api_key>
export PINECONE_INDEX_URL=<your_pinecone_index_url>
The index URL looks like: https://my-index-abcdef.svc.us-east-1-aws.pinecone.io
.env file and load them with source .env or a tool like direnv. Never commit API keys to version control.
Quickstart
This guide takes you from zero to a running AutoGPT agent in under 5 minutes, using the Gemini provider and the ArchitectGPT built-in agent.
Prerequisites
- Rust 1.89+ (
rustup update stable). - A Gemini API key.
Step 1: Set your API key
export GEMINI_API_KEY=<your_gemini_api_key>
Step 2: Create a new Rust project
cargo new my-agent && cd my-agent
Add AutoGPT to Cargo.toml:
[dependencies]
autogpt = { version = "0.4.5", features = ["gem", "gpt"] }
tokio = { version = "1", features = ["full"] }
Step 3: Write your first agent
Replace src/main.rs with:
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let persona = "Lead UX/UI Designer";
let behavior = r#"Generate a diagram for a simple web application running on Kubernetes.
It consists of a single Deployment with 2 replicas, a Service to expose the Deployment,
and an Ingress to route external traffic. Also include a basic monitoring setup
with Prometheus and Grafana."#;
let agent = ArchitectGPT::new(persona, behavior).await;
let autogpt = AutoGPT::default()
.with(agents![agent])
.build()
.expect("Failed to build AutoGPT");
match autogpt.run().await {
Ok(response) => println!("{}", response),
Err(err) => eprintln!("Agent error: {:?}", err),
}
}
Step 4: Run it
cargo run
AutoGPT calls Gemini, generates Python diagrams-library code, and writes it to:
workspace/architect/diagram.py
Step 5: Render the diagram
./workspace/architect/.venv/bin/python ./workspace/architect/diagram.py
A PNG architecture diagram appears in workspace/architect/.
export AI_PROVIDER=openai and export OPENAI_API_KEY=..., then change the feature flag to features = ["oai", "gpt"].
Running Multiple Agents in Parallel
The agents! macro accepts any number of agents. AutoGPT runs them concurrently using Tokio tasks:
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let architect = ArchitectGPT::new(
"Software Architect",
"Design a microservices architecture for an e-commerce platform.",
).await;
let backend = BackendGPT::new(
"Backend Developer",
"Generate a REST API for user authentication in Rust using axum.",
"rust",
).await;
let autogpt = AutoGPT::default()
.with(agents![architect, backend])
.build()
.expect("Failed to build AutoGPT");
match autogpt.run().await {
Ok(msg) => println!("{}", msg),
Err(e) => eprintln!("{:?}", e),
}
}
Both agents execute concurrently and their outputs land in their respective workspace directories.
Next Steps
- Configuration β: set up memory, email, and image generation.
- Custom Agents β: build agents tailored to your domain.
- Interactive Mode β: chat with AutoGPT from the terminal.
Interactive Mode
Running autogpt with no arguments launches GenericGPT, a full-featured conversational AI shell with session persistence, runtime model switching, and multi-provider support.
autogpt
This is the default mode and requires no subcommands or flags.
Shell Commands
Once inside the shell, the following commands are available:
| Command | Description |
|---|---|
<your prompt> | Send a message to the active AI agent |
/help | Show all available shell commands |
/provider | Switch LLM provider at runtime (Gemini, OpenAI, Anthropic, XAI, Cohere, HuggingFace) |
/models | Browse and switch between models supported by the active provider |
/sessions | List and resume previous conversation sessions |
/status | Show the current model, provider, and workspace directory |
/workspace | Print the current workspace path |
/clear | Clear the terminal screen |
exit / quit | Save the session and exit |
ESC at any time to interrupt a running generation without closing the shell.
Session Management
Every conversation is automatically saved as a YAML file inside your workspace. When you type /sessions, AutoGPT lists all previous sessions. Selecting one restores the full conversation history, so the agent retains context from where you left off.
Sessions are stored under the .autogpt/sessions/ directory and indexed by a UUID, creation timestamp, and a short automatic summary. See the GenericGPT agent page for full detail on the .autogpt directory layout.
Switching Providers at Runtime
You can switch between LLM providers without restarting the shell:
> /provider
1. Gemini (active)
2. OpenAI
3. Anthropic
4. XAI
5. Cohere
6. HuggingFace
Select provider: 2
β Switched to OpenAI
Switching providers also reloads the model list for the new provider and resets the active model to that providerβs default.
The selected provider must have its API key set as an environment variable and its corresponding Cargo feature enabled at compile time.
Switching Models
/models lists all models available from the active provider, sourced directly from each providerβs crate. Use arrow keys to navigate and Enter to confirm:
> /models
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Flash3Preview
Pro31Preview
Flash31LitePreview
...
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Model set to: Flash3Preview
Override the default model using environment variables instead of the interactive selector:
export GEMINI_MODEL=gemini-2.5-pro-preview-05-06
How GenericGPT Works
GenericGPT is a production-hardened autonomous agent that goes well beyond simple chat:
- Reasoning pre-step: Before acting, the agent emits a structured internal monologue (stored in the session log) to plan its approach.
- Task synthesis: The plan is decomposed into an ordered list of typed actions (
CreateFile,PatchFile,RunCommand, etc.). - Execution: Each action is applied against the workspace.
PatchFileperforms anchor-text surgical edits;RunCommandruns shell commands. - Build-and-verify: After code changes, the agent detects the projectβs build system (
cargo,npm, etc.) and runs it. On failure, it feeds the error back and retries automatically (up to 3 attempts). - Reflection: After completion the agent reviews what worked and what didnβt.
- Skill extraction: Lessons are written to provider-specific TOML files in
.autogpt/skills/and injected into future sessions automatically.
The cli feature flag must be enabled to use the interactive shell:
cargo install autogpt --features cli,gem
Direct Prompt Mode
Direct Prompt Mode lets you send a single prompt to the active LLM provider and receive an immediate response, no agents, no configuration, no interactive shell. It is the fastest way to query your AI provider from the terminal.
autogpt -p "<your prompt>"
Examples
Ask a factual question:
autogpt -p "Explain the Rust borrow checker in simple terms"
Generate a code snippet:
autogpt -p "Write a Rust function that reads a file and returns its contents as a String"
Summarize text (pipe from stdin via shell substitution):
autogpt -p "Summarize the following text: $(cat /path/to/document.txt)"
When to Use Direct Prompt Mode
Direct Prompt Mode is ideal when you want:
- A quick one-shot answer without starting the interactive shell.
- To script AutoGPT into shell pipelines or CI workflows.
- To verify your API key and provider are working correctly.
Provider Selection
Direct Prompt Mode respects the AI_PROVIDER environment variable:
AI_PROVIDER=openai autogpt -p "What is the capital of France?"
The -p flag uses the same client initialization as the interactive shell, so all provider API keys and model environment variables apply.
Output
The response is printed to stdout with no extra formatting. This makes it easy to pipe into other tools:
autogpt -p "Write a haiku about Rust" | cowsay
Standalone Mode
In Standalone Mode you run a single specialized agent directly via a CLI subcommand. Each agent operates independently, no orchestrator, no network, no IAC protocol. This is the simplest way to use the specialized built-in agents.
Available Subcommands
| Subcommand | Agent | Purpose |
|---|---|---|
autogpt arch | ArchitectGPT | Generate architecture diagrams |
autogpt back | BackendGPT | Generate backend source code |
autogpt front | FrontendGPT | Generate frontend UI code |
autogpt design | DesignerGPT | Generate UI design images |
autogpt man | ManagerGPT | Orchestrate all other agents locally |
Example: Architecture Diagram
autogpt arch
AutoGPT prompts you for a project goal, passes it to ArchitectGPT, which generates Python diagrams-library code in workspace/architect/. Run the output to produce a PNG:
./workspace/architect/.venv/bin/python ./workspace/architect/diagram.py
Example: Full-Stack Code Generation via ManagerGPT
autogpt man
Enter your project goal when prompted:
> Develop a full-stack todo app in Rust using Axum for the backend and Yew for the frontend.
ManagerGPT decomposes the goal and dispatches subtasks to BackendGPT, FrontendGPT, and ArchitectGPT in parallel. The generated code lands in:
workspace/
βββ architect/ # architecture diagram
βββ backend/ # Rust Axum server code
βββ frontend/ # Yew component code
Task Lifecycle
When running in Standalone Mode, each agent follows this lifecycle:
User Input β Task Construction β Agent Execution β File Write β Done
- User Input: You provide a project goal as a prompt.
- Task Construction: AutoGPT wraps the goal into a
Taskstruct with aScopecontrolling CRUD, auth, and external access permissions. - Agent Execution: The agent calls the configured LLM, processes the response, and handles retries (
max_tries). - File Write: Generated artifacts are written to the workspace directory.
- Done: The process exits cleanly.
Scope Permissions
When using the SDK in Standalone Mode, you can restrict what agents are allowed to do:
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let agent = BackendGPT::new("Backend Dev", "Write a Rust HTTP server.", "rust").await;
let autogpt = AutoGPT::default()
.with(agents![agent])
.crud(true)
.auth(false) // No auth-related code
.external(true) // Allow external API calls
.max_tries(3) // Retry up to 3 times on failure
.build()
.expect("Failed to build AutoGPT");
autogpt.run().await.unwrap();
}
max_tries when working with complex prompts. Agents automatically detect and fix compilation or logic errors across retry attempts.
Orchestrated Mode
Orchestrated Mode connects autogpt agents to an external orchgpt orchestrator over a secure TLS-encrypted TCP channel. This enables distributed, multi-agent collaboration across machines, not just locally.
Starting the Orchestrator
On the host that will coordinate agents, start orchgpt:
orchgpt
By default it binds to 0.0.0.0:8443. To use a different address:
export ORCHESTRATOR_ADDRESS=0.0.0.0:9443
orchgpt
Connecting an Agent
In a separate terminal (or on another machine), connect autogpt to the running orchestrator:
autogpt --net
autogpt resolves the orchestrator address from ORCHESTRATOR_ADDRESS and establishes a TLS session using the IAC protocol.
Sending Commands
Once connected, you interact with agents using this command syntax:
/<agent_name> <action> "<payload>" | <language>
Examples:
# Create an ArchitectGPT agent for a FastAPI app using Python
/arch create "fastapi app" | python
# Create a BackendGPT agent for a REST API in Rust
/back create "user auth REST API" | rust
# Create a FrontendGPT agent for a React app
/front create "dashboard UI with charts" | javascript
Each command sends an IAC Message with:
| Field | Value |
|---|---|
msg_type | create |
to | ArchitectGPT / BackendGPT / etc. |
payload_json | Your project goal string |
language | Target programming language |
Communication Flow
βββββββββββ TLS+TCP (IAC) ββββββββββββββββ IAC ββββββββββββββ
β autogpt β βββββββββββββββββΆ β orchgpt β βββββββΆ β AgentGPTs β
β (CLI) β βββββββββββββββββ β(Orchestrator)β βββββββ β (workers) β
βββββββββββ Responses ββββββββββββββββ ββββββββββββββ
All messages travel over TLS 1.3 and are encoded in Protocol Buffers. Every message is signed with Ed25519 to verify agent identity. See IAC Protocol for full details.
Running via Docker Compose
The included docker-compose.yml sets up both services with a shared network:
docker compose up --build
This builds and starts:
autogptcontainer, the agent.orchgptcontainer, the orchestrator.
Docker Compose configures the internal network automatically, so autogpt can reach orchgpt by container name.
Using the SDK for Networked Agents
Enable the net feature flag and use the Collaborator type to register remote agents:
use autogpt::prelude::*;
use std::collections::HashMap;
#[tokio::main]
async fn main() -> Result<()> {
let addr = "127.0.0.1:4555";
let signer = Signer::new(KeyPair::generate());
let client = Client::connect(addr, signer.clone()).await?;
let mut clients = HashMap::new();
clients.insert("frontend".into(), Arc::new(Mutex::new(client.clone())));
let mut agent = AgentGPT::new("Design software".into(), "designer".into());
agent.signer = signer;
agent.clients = clients;
agent.addr = addr.into();
agent.capabilities.insert(Capability::CodeGen);
agent.broadcast_capabilities().await?;
Ok(())
}
Built-in Agents Overview
AutoGPT 0.2 ships with 9 built-in autonomous agents, each specializing in a different domain. They are independently usable via CLI subcommands and composable via the SDKβs agents! macro.
Agent Roster
| Agent | Feature Flag | CLI Subcommand | Role |
|---|---|---|---|
GenericGPT | cli | (default, no subcommand) | Autonomous software engineering: reasons, edits files, builds, learns |
ManagerGPT | gpt | autogpt man | Task orchestration across all agents |
ArchitectGPT | gpt | autogpt arch | System architecture diagram generation |
BackendGPT | gpt | autogpt back | Backend source code generation |
FrontendGPT | gpt | autogpt front | Frontend UI code generation |
DesignerGPT | img | autogpt design | AI image and UI mockup generation |
GitGPT | git | (automatic) | Atomic Git commits from agent output |
MailerGPT | mail | (SDK only) | Email reading and automated sending |
OptimizerGPT | gpt | (SDK only) | Codebase modularization and refactoring |
Agent Architecture
Every agent in AutoGPT is built from three composable layers:
βββββββββββββββββββββββββββββββββββββββββββ
β Agent Struct β
β (e.g. ArchitectGPT, BackendGPT, etc.) β
βββββββββββββββββββββββββββββββββββββββββββ€
β AgentGPT Core β
β persona Β· behavior Β· memory Β· status β
β tools Β· knowledge Β· planner Β· context β
βββββββββββββββββββββββββββββββββββββββββββ€
β ClientType (LLM Client) β
β Gemini Β· OpenAI Β· Claude Β· XAI Β· Co β
βββββββββββββββββββββββββββββββββββββββββββ
AgentGPT: the universal agent state: persona string, behavior string, conversation memory, status, tools, planner, and context managerClientType: an enum wrapping the active LLM client (Gemini Flash, GPT-4o, Claude 3.5, etc.)Executorimpl: the agent-specific logic: what to do with the LLM response (write files, commit code, send email, etc.)
Composing Multiple Agents
All agents conform to the AgentFunctions trait, making them interchangeable inside the agents! macro:
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let architect = ArchitectGPT::new(
"Software Architect",
"Design a microservices diagram for a payment gateway.",
).await;
let backend = BackendGPT::new(
"Backend Engineer",
"Generate a payment processing API in Rust with axum.",
"rust",
).await;
let frontend = FrontendGPT::new(
"Frontend Developer",
"Build a React checkout form that calls the payment API.",
"javascript",
).await;
AutoGPT::default()
.with(agents![architect, backend, frontend])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
All three agents run concurrently using Tokio tasks. There is no sequential bottleneck.
Agent Status Lifecycle
Every agent transitions through these states:
| Status | Meaning |
|---|---|
Idle | Initialized, waiting to run |
Active | Executing its task |
Completed | Task finished successfully |
Error | Task failed (triggers retry if max_tries > 1) |
You can inspect status programmatically after a run:
let guard = autogpt.agents[0].lock().await;
let agent = guard.get_agent();
println!("Status: {:?}", agent.status());
println!("Memory length: {}", agent.memory().len());
GenericGPT
GenericGPT is the autonomous, self-improving software engineering agent that powers AutoGPTβs default interactive shell. It is the primary agent a developer interacts with when running autogpt with no subcommands.
Unlike the specialised agents (BackendGPT, FrontendGPT, etc.) that each own a single discipline, GenericGPT is a generalist: it reasons about its task, decomposes it into steps, writes or edits files surgically, runs the projectβs build system, and learns from the outcome, all autonomously.
Capabilities
| Capability | Description |
|---|---|
| Reasoning pre-step | Plans before acting; emits a structured internal monologue before every task |
| File tooling | CreateFile, WriteFile, PatchFile, ReadFile, AppendFile, ListDir, FindInFile |
| Shell execution | RunCommand runs arbitrary shell commands inside the workspace |
| Build-and-verify | Detects the build system (cargo, npm, python, β¦) and iterates on errors |
| Git commits | GitCommit action commits changes with a generated message |
| Persistent skills | Learns lessons across sessions and injects them into future prompts |
| Session continuity | Full conversation history is restored when you resume a session |
| Multi-provider | Switches between Gemini, OpenAI, Anthropic, xAI, Cohere, and HuggingFace at runtime |
The .autogpt Directory
GenericGPT maintains a hidden directory at its state root (typically ~/.autogpt/, but controlled by the AUTOGPT_WORKSPACE environment variable) that stores all persistent state:
~/.autogpt/
βββ sessions/ # Markdown conversation snapshots, auto-saved after every response
β βββ <uuid>.md
β βββ ...
βββ skills/ # Learned lessons (TOML)
βββ rust.toml
βββ web.toml
βββ python.toml
βββ ...
Working directory: GenericGPT defaults its workspace to the current directory where the CLI is launched. Set
AUTOGPT_WORKSPACEto override:export AUTOGPT_WORKSPACE=/my/project autogpt # all file operations are scoped to /my/project
Skills: Cross-Session Learning
After each task, GenericGPT extracts lessons and stores them in TOML skill files under skills/. The agent auto-detects the current project domain and injects only the relevant lessons into the system prompt for the next session, avoiding past mistakes automatically.
Skill files are plain TOML and can be inspected or edited:
# ~/.autogpt/skills/rust.toml
[[lessons]]
title = "Use PatchFile over WriteFile for edits"
detail = "Anchor-text patching is safer than full rewrites for large files."
added_at = "2026-05-06T14:50:00Z"
uses = 4
Session Management
Sessions are stored as YAML files and indexed by UUID. Resume a past session from within the shell:
> /sessions
1. "Implement a REST API in Rust using axum" (8/10 tasks) 2026-05-06
2. "Build a React dashboard with auth" (3/5 tasks) 2026-05-05
> Enter number to resume: 1
β Resumed session - 8 tasks completed, 2 remaining.
Build-and-Verify Loop
After writing code, GenericGPT detects the build system and runs it automatically:
| Build system | Detection signal | Command run |
|---|---|---|
| Cargo | Cargo.toml | cargo build |
| npm / Node | package.json | npm run build |
| Python | pyproject.toml / requirements.txt | python -m py_compile |
| Make | Makefile | make |
If the build fails, the error output is fed back into the agentβs context and it attempts an automated fix, up to 3 times, before reporting the failure to you.
Execution Flow
flowchart TD
A([User enters prompt]) --> B[Reasoning pre-step\nPlan & decompose]
B --> C[Task synthesis\nBreak into ordered actions]
C --> D{User approves plan?}
D -- yolo mode --> E
D -- Yes --> E[Execute actions in order]
E --> F{Actions complete?}
F -- File write --> G[Build-and-verify loop]
G -- Pass --> H[Reflection & lesson extraction]
G -- Fail, retry β€3 --> E
F -- Other --> H
H --> I[Save skills to disk]
I --> J[Save session to disk]
J --> K([Ready for next prompt])
Environment Variables
| Variable | Default | Description |
|---|---|---|
AI_PROVIDER | gemini | Active LLM provider |
AUTOGPT_WORKSPACE | . (cwd) | Workspace root where files are written |
GEMINI_MODEL | (first in list) | Override the active Gemini model |
OPENAI_MODEL | (first in list) | Override the active OpenAI model |
ANTHROPIC_MODEL | (first in list) | Override the active Anthropic model |
XAI_MODEL | (first in list) | Override the active xAI model |
COHERE_MODEL | (first in list) | Override the active Cohere model |
HF_MODEL | (first in list) | Override the active HuggingFace model |
MODEL | (global fallback) | Global model override for any provider |
Feature Flags
GenericGPT and the interactive shell require the cli feature plus at least one provider feature:
# Gemini (recommended)
cargo install autogpt --features cli,gem
# OpenAI
cargo install autogpt --features cli,oai
# All providers
cargo install autogpt --all-features
ManagerGPT
Feature: gpt CLI: autogpt man
ManagerGPT is the top-level orchestrator in the AutoGPT agent mesh. It receives a high-level project goal, decomposes it into discrete subtasks, assigns each subtask to the appropriate specialist agent, and consolidates their outputs into a coherent final result.
What ManagerGPT Solves
Complex software projects involve multiple domains, e.g. architecture, backend, frontend, design, that must be developed in a coordinated way. ManagerGPT eliminates the need to manually decompose tasks and coordinate specialists. You give it one goal; it handles the rest.
How It Works
User Goal
β
βΌ
ManagerGPT (decomposes)
β
ββββΆ ArchitectGPT β Architecture diagram
ββββΆ BackendGPT β Server-side code
ββββΆ FrontendGPT β UI code
ββββΆ DesignerGPT β UI mockups (optional)
β
βΌ
ManagerGPT (consolidates)
β
βΌ
Final Output to User
ManagerGPT communicates its decomposed subtasks to each agent by constructing specialized Task descriptions enriched with the original goal context. Each agent receives not just its slice of the work but enough context to make coherent decisions.
CLI Usage
autogpt man
AutoGPT prompts for your project goal interactively. For example:
> Develop a full stack app that fetches today's weather in Python using FastAPI.
ManagerGPT dispatches to ArchitectGPT, DesignerGPT, BackendGPT, and FrontendGPT. Terminal output:
[*] "ManagerGPT": Executing task: "Develop a full stack app that fetches today's weather in python using FastAPI."
[*] "ArchitectGPT": Executing tasks: Task { description: "- Design the user interface for the weather app..." }
[*] "BackendGPT": Executing tasks: Task { description: "- Using FastAPI in Python, create a backend..." }
[*] "FrontendGPT": Executing tasks: Task { description: "- Using FastAPI in Python, create a user interface..." }
[*] "ManagerGPT": Completed Task: Task { ... }
SDK Usage
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let persona = "Project Manager";
let behavior = "Develop a full-stack weather app in Python using FastAPI.";
let agent = ManagerGPT::new(persona, behavior).await;
AutoGPT::default()
.with(agents![agent])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
Output
Generated code lands in the workspace directory, organized by agent:
workspace/
βββ architect/ # Python diagrams code
βββ backend/ # FastAPI backend
βββ frontend/ # HTML/CSS/JS frontend
βββ designer/ # UI mockup images (if img feature enabled)
ArchitectGPT
Feature: gpt CLI: autogpt arch
ArchitectGPT translates a high-level project description into a concrete system architecture. It determines the technologies, frameworks, and communication patterns needed, then generates an executable Python script using the diagrams library that renders a PNG architecture diagram.
What ArchitectGPT Solves
Software architecture decisions are typically made informally and documented inconsistently. ArchitectGPT externalizes this process: given a goal, it produces a versioned, reproducible visual diagram that serves as the authoritative architectural reference for all other agents.
How It Works
- ArchitectGPT receives a project goal from ManagerGPT or directly from the user
- It calls the configured LLM to generate a Python script using the
diagramslibrary - The script is written to
workspace/architect/diagram.py - A Python virtual environment is set up with
diagramsinstalled inworkspace/architect/.venv/ - Running the script produces a PNG in that directory
CLI Usage
autogpt arch
Example session:
> Generate a Kubernetes architecture for a web app with Prometheus and Grafana monitoring.
After the agent completes:
# Render the diagram
./workspace/architect/.venv/bin/python ./workspace/architect/diagram.py
# β simple_web_application_on_kubernetes.png created
SDK Usage
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let persona = "Lead UX/UI Designer";
let behavior = r#"Generate a diagram for a simple web application running on Kubernetes.
It consists of a single Deployment with 2 replicas, a Service to expose the Deployment,
and an Ingress to route external traffic. Also include a basic monitoring setup
with Prometheus and Grafana."#;
let agent = ArchitectGPT::new(persona, behavior).await;
AutoGPT::default()
.with(agents![agent])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
Output
workspace/architect/
βββ .venv/ # Python venv with diagrams installed
βββ diagram.py # Generated diagrams script
βββ *.png # Rendered architecture diagram
BackendGPT
Feature: gpt CLI: autogpt back
BackendGPT specializes in generating production-ready server-side code. Given a project goal and a target language, it generates complete backend implementations including API endpoints, data models, database integrations, authentication logic, and dependency configurations.
What BackendGPT Solves
Writing boilerplate backend code, e.g. route handlers, middleware, schema definitions, Docker configurations is time-consuming and predictable. BackendGPT generates this scaffolding instantly, correctly structured for the chosen language and framework, so you can focus on business logic.
Supported Languages
BackendGPT accepts any programming language string. The LLM adapts its output accordingly. Common examples:
| Language | Typical Output |
|---|---|
rust | Axum/Actix-web server with Cargo.toml |
python | FastAPI or Flask app with requirements.txt |
javascript | Express.js or Fastify app with package.json |
CLI Usage
autogpt back
You will be prompted for a language and project goal.
SDK Usage
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let persona = "Backend Developer";
let behavior = "Develop a weather backend API in Rust using axum.";
let agent = BackendGPT::new(persona, behavior, "rust").await;
AutoGPT::default()
.with(agents![agent])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
The third argument to BackendGPT::new is the target programming language.
Output
workspace/backend/
βββ main.py # (Python) Application entry point
βββ template.py # (Python) Template/model definitions
βββ ... # Additional files based on the project
For Rust projects the generated files are placed as a complete Cargo project structure.
Retry Behavior
BackendGPT attempts to compile and validate the generated code when execute is enabled. If compilation fails it automatically retries up to max_tries times, passing the compiler error back to the LLM for correction.
AutoGPT::default()
.with(agents![agent])
.max_tries(3) // retry up to 3 times on compile failure
.build()
.unwrap()
.run()
.await
.unwrap();
FrontendGPT
Feature: gpt CLI: autogpt front
FrontendGPT generates complete frontend user interface code for web applications. It produces HTML, CSS, JavaScript, and framework-specific components, responsive by default and styled appropriately for the described use case.
What FrontendGPT Solves
Translating a feature description into a working, well-structured UI requires decisions about layout, component hierarchy, data binding, and styling. FrontendGPT makes those decisions automatically, generating a complete starting point rather than skeleton files.
Supported Stacks
FrontendGPT accepts the programming language / framework as a string:
| Value | Output |
|---|---|
javascript | Vanilla HTML/CSS/JS or React/Vue based on context |
react | React component tree with JSX |
python | Jinja2 HTML templates (for FastAPI/Flask) |
rust | Yew WASM components |
CLI Usage
autogpt front
SDK Usage
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let persona = "UX/UI Designer";
let behavior = "Generate UI for a weather app using React JS.";
let agent = FrontendGPT::new(persona, behavior, "javascript").await;
AutoGPT::default()
.with(agents![agent])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
Output
workspace/frontend/
βββ main.py # (Python) Template renderer entry point
βββ template.py # (Python) Jinja2 templates
βββ ... # HTML/CSS/JS files for JS-based projects
Pairing with BackendGPT
FrontendGPT is aware of the backend API schema when run via ManagerGPT. This means the generated frontend code calls the correct API endpoints defined by BackendGPT, producing a cohesive full-stack result.
DesignerGPT
Feature: img CLI: autogpt design
DesignerGPT generates visual UI mockups and design assets using an AI image generation API (GetImg). It transforms a textual interface description into a rendered image that can be used as a design reference for frontend development.
What DesignerGPT Solves
Getting sign-off on UI layout before any code is written saves significant rework. DesignerGPT generates visual mockups from natural language descriptions in seconds, enabling rapid design iteration without a designer in the loop.
Enabling DesignerGPT
DesignerGPT requires the img feature flag and the GETIMG_API_KEY environment variable:
cargo install autogpt --features img,cli
export GETIMG_API_KEY=<your_getimg_api_key>
Obtain your API key from the GetImg Dashboard.
CLI Usage
autogpt design
Describe the UI you want to generate when prompted:
> A dark-themed dashboard with a sidebar navigation, metrics cards, and a chart area
SDK Usage
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let persona = "Senior UI/UX Designer";
let behavior = "Design a modern dark-themed analytics dashboard with sidebar navigation.";
let agent = DesignerGPT::new(persona, behavior).await;
AutoGPT::default()
.with(agents![agent])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
Output
Generated image files land in:
workspace/designer/
βββ design_<timestamp>.png
img feature, it simply skips the design step and proceeds with architecture, backend, and frontend.
GitGPT
Feature: git
GitGPT automates version control by creating atomic Git commits whenever an agent completes a task. It monitors agent status, stages the entire workspace, and commits with a structured message that traces the commit back to the original user goal and agent role.
What GitGPT Solves
In autonomous or quasi-autonomous workflows, tracking what changed and why is difficult without discipline. GitGPT enforces a clean, auditable Git history automatically, every agent action becomes a commit with a descriptive, machine-generated message.
Enabling GitGPT
cargo install autogpt --features git,gem,gpt
AUTOGPT_WORKSPACE must point to a directory that is a Git repository (or within one).
How It Works
GitGPT runs after each agent completes. It:
- Checks if the agent status is
Completed - Stages all modified files (
git add .) in the workspace - Computes a structured commit message from the task description and agent role
- Creates a signed commit using
GitGPT <gitgpt@wiseai.dev>as the author
Example Commit Message
commit cc448377fae752ba28847c873751ba1170d19fc0 (HEAD -> master)
Author: GitGPT <gitgpt@wiseai.dev>
Date: Mon Apr 7 00:25:59 2025 +0300
User Request: Project Goal: "Develop a patient management system
encompassing appointment scheduling, patient records, and billing features.",
Agent Role: "frontend", programming language: "Python", framework: "FastAPI"
Output:
- Implementing FastAPI, construct a frontend in Python for a patient
management system encompassing appointment scheduling, patient records,
and billing features.
- Step 1: Develop the user interface components for appointment scheduling.
- Step 2: Build the UI for managing and displaying patient records.
- Step 3: Create the billing interface for generating and displaying invoices.
SDK Usage
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let backend = BackendGPT::new(
"Backend Developer",
"Generate a REST API for a blog in Python using FastAPI.",
"python",
).await;
let git_agent = GitGPT::new("GitGPT", "Commit backend changes").await;
AutoGPT::default()
.with(agents![backend, git_agent])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
git init workspace/ && git -C workspace/ commit --allow-empty -m "init"
MailerGPT
Feature: mail
MailerGPT integrates with the Nylas email API to read, parse, and send emails autonomously. It extracts relevant information from incoming messages and generates personalized outgoing email content based on user-defined goals.
What MailerGPT Solves
Automating email workflows typically requires complex IMAP/SMTP integrations with fragile parsing logic. MailerGPT uses the Nylas unified API to abstract email providers and the LLM to handle content understanding and generation, turning natural language goals into fully composed emails.
Enabling MailerGPT
MailerGPT requires the mail feature flag and three Nylas environment variables:
cargo install autogpt --features mail,gem
export NYLAS_SYSTEM_TOKEN=<your_nylas_system_token>
export NYLAS_CLIENT_ID=<your_nylas_client_id>
export NYLAS_CLIENT_SECRET=<your_nylas_client_secret>
Follow the Nylas setup guide to obtain these credentials.
How It Works
- MailerGPT connects to the Nylas API using the configured credentials
- It reads emails from the configured inbox and parses their content
- Based on the agentβs
behaviorgoal, it composes reply or new outbound email content using the LLM - It sends the generated email via the Nylas API
SDK Usage
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let persona = "Customer Support Agent";
let behavior = "Read incoming support emails and draft polite, helpful replies.";
let agent = MailerGPT::new(persona, behavior).await;
AutoGPT::default()
.with(agents![agent])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
OptimizerGPT
Feature: gpt
OptimizerGPT refactors messy or monolithic code files into clean, well-organized, modular structures. It reads a single large source file, identifies logical separation of concerns, and rewrites it as a set of focused modules following framework conventions.
What OptimizerGPT Solves
Agent-generated code (from BackendGPT or FrontendGPT) often starts as a single large file to satisfy the LLM context window. OptimizerGPT acts as a post-processor to enforce real-world code organization, splitting routes from handlers, models from services, and utilities from application logic.
How It Works
- OptimizerGPT receives a file path pointing to a monolithic source file
- It sends the file contents to the LLM with instructions to identify logical modules
- The LLM returns a restructured file layout following standard conventions for the target stack
- OptimizerGPT writes the new module files to the workspace, preserving the original
Supported Stacks
OptimizerGPT works with any language. It applies framework-idiomatic conventions when it recognizes the stack:
| Stack | Resulting Structure |
|---|---|
| FastAPI (Python) | routes/, models/, services/, utils/ |
| Axum (Rust) | routes.rs, models.rs, handlers.rs, state.rs |
| React (JS) | components/, hooks/, services/, utils/ |
| Express (JS) | routes/, controllers/, middleware/, models/ |
SDK Usage
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let persona = "Senior Software Engineer";
let behavior = "Refactor workspace/backend/main.py into a clean FastAPI project structure.";
let agent = OptimizerGPT::new(persona, behavior).await;
AutoGPT::default()
.with(agents![agent])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
Pipeline Integration
OptimizerGPT pairs naturally after BackendGPT or FrontendGPT in an agents! list. Because AutoGPT runs agents concurrently, chain them sequentially when order matters:
let backend = BackendGPT::new("Dev", "Build a user auth API in Rust with axum.", "rust").await;
AutoGPT::default()
.with(agents![backend])
.build().unwrap()
.run().await.unwrap();
let optimizer = OptimizerGPT::new(
"Refactor Expert",
"Modularize workspace/backend/main.rs into idiomatic axum structure.",
).await;
AutoGPT::default()
.with(agents![optimizer])
.build().unwrap()
.run().await.unwrap();
SDK Overview
The AutoGPT SDK lets you embed the full agent framework as a library in your own Rust applications. You compose agents, configure the runner, and call run(), all with async/await and Tokio.
Adding the Dependency
[dependencies]
autogpt = { version = "0.4.3", features = ["gem", "gpt"] }
tokio = { version = "1", features = ["full"] }
All types needed for typical usage are re-exported through autogpt::prelude::*.
The AutoGPT Struct
AutoGPT is the top-level orchestration handle. It holds a list of agents and controls how they run:
use autogpt::prelude::*;
let autogpt = AutoGPT::default()
.with(agents![agent_a, agent_b]) // register agents
.execute(true) // enable task execution (default: true)
.browse(false) // disable browser access (default: false)
.max_tries(3) // retry failed agents up to 3 times
.crud(true) // allow CRUD operations in scope
.auth(false) // no auth-related code generation
.external(true) // allow external API calls
.build()
.expect("Failed to build AutoGPT");
Running Agents
run() spawns one Tokio task per agent and runs them concurrently:
match autogpt.run().await {
Ok(msg) => println!("{}", msg), // "All agents executed successfully."
Err(e) => eprintln!("{:?}", e),
}
If any agent fails all its retry attempts, run() returns an Err containing all failure messages joined into a single string.
Inspecting Agent State After Execution
After run() returns, you can inspect each agentβs in-memory state:
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let agent = ArchitectGPT::new("Architect", "Design a Kubernetes cluster.").await;
let autogpt = AutoGPT::default()
.with(agents![agent])
.build()
.unwrap();
autogpt.run().await.unwrap();
let guard = autogpt.agents[0].lock().await;
let agent_state = guard.get_agent();
println!("Status: {:?}", agent_state.status());
println!("Memory: {} messages", agent_state.memory().len());
for msg in agent_state.memory() {
println!("[{}] {}", msg.role, msg.content);
}
}
Accessing Long-Term Memory
With the mem feature, retrieve persisted Pinecone memories:
let memories = guard.get_ltm().await.unwrap();
println!("LTM messages: {}", memories.len());
See Long-Term Memory for full setup.
AutoGPT Builder
The AutoGPT struct uses a builder pattern to configure the runtime before executing agents. All builder methods consume and return Self, enabling method chaining.
Builder Methods
| Method | Type | Default | Description |
|---|---|---|---|
.with(agents) | impl Into<Vec<...>> | - | Register agents to run |
.execute(bool) | bool | true | Enable agent task execution |
.browse(bool) | bool | false | Allow agents to open browser windows |
.max_tries(u64) | u64 | 1 | Max retry attempts per agent on failure |
.crud(bool) | bool | true | Allow CRUD file operations in scope |
.auth(bool) | bool | false | Allow auth-related code generation |
.external(bool) | bool | true | Allow calls to external APIs |
.id(Uuid) | Uuid | random | Override the AutoGPT instance UUID |
.build() | Result<Self> | - | Validate and build the instance |
Full Builder Example
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let agent = BackendGPT::new(
"Senior Engineer",
"Generate a secure user authentication API in Rust.",
"rust",
).await;
let autogpt = AutoGPT::default()
.with(agents![agent])
.execute(true)
.browse(false)
.max_tries(3)
.crud(true)
.auth(true) // auth-related code allowed
.external(false) // no external network calls
.build()
.expect("Failed to build AutoGPT");
autogpt.run().await.unwrap();
}
Scope: How Permissions Flow to Agents
When .build() is called, a Scope struct is constructed from the crud, auth, and external values:
pub struct Scope {
pub crud: bool,
pub auth: bool,
pub external: bool,
}
This Scope is included in every Task dispatched to each agent. Agents can inspect it in their Executor::execute implementation to decide whether certain operations are permitted.
Running Multiple Agent Groups Sequentially
Each AutoGPT instance is independent. Chain .run() calls to enforce ordering:
// Phase 1: generate backend
let phase1 = AutoGPT::default()
.with(agents![BackendGPT::new("Dev", "REST API in Rust.", "rust").await])
.build().unwrap();
phase1.run().await.unwrap();
// Phase 2: optimize the output of phase 1
let phase2 = AutoGPT::default()
.with(agents![OptimizerGPT::new("Refactorer", "Modularize workspace/backend/main.rs.").await])
.build().unwrap();
phase2.run().await.unwrap();
Error Handling
.build() returns Result<AutoGPT, anyhow::Error>. Currently validation is lightweight, it succeeds as long as required feature flags are compiled in. .run() returns Result<String, anyhow::Error> where the Err variant contains all agent failure messages joined with newlines.
Creating Custom Agents
AutoGPTβs most powerful feature is the ability to compose any agent from scratch using the Auto derive macro and the Executor trait. Your custom agent participates in the same runtime as the built-in agents; It can be passed to agents!, run concurrently, and use the full LLM client API.
The Minimum Required Shape
A custom agent struct needs exactly two fields:
use autogpt::prelude::*;
#[derive(Debug, Default, Auto)]
pub struct MyAgent {
pub agent: AgentGPT, // Core agent state
pub client: ClientType, // LLM client (Gemini, OpenAI, etc.)
}
The Auto derive macro implements Agent, Functions, AsyncFunctions, and AgentFunctions for you automatically. You only need to implement Executor with your custom logic.
Implementing Executor
Executor has one required method, execute. This is where your agent does its work:
use autogpt::prelude::*;
#[derive(Debug, Default, Auto)]
pub struct SummarizerAgent {
pub agent: AgentGPT,
pub client: ClientType,
}
#[async_trait]
impl Executor for SummarizerAgent {
async fn execute<'a>(
&'a mut self,
task: &'a mut Task,
execute: bool,
browse: bool,
max_tries: u64,
) -> Result<()> {
let prompt = self.agent.behavior().clone();
let response = self.generate(prompt.as_ref()).await?;
self.agent.add_message(Message {
role: "assistant".into(),
content: response.clone().into(),
});
let _ = self.save_ltm(Message {
role: "assistant".into(),
content: response.clone().into(),
}).await;
println!("{}", response);
Ok(())
}
}
Running Your Custom Agent
#[tokio::main]
async fn main() {
let persona = "Technical Writer";
let behavior = "Summarize the Rust ownership model for a beginner audience.";
let agent = SummarizerAgent::new(persona.into(), behavior.into());
AutoGPT::default()
.with(agents![agent])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
Mixing Custom and Built-in Agents
Custom agents are fully interchangeable with built-in ones:
let architect = ArchitectGPT::new("Architect", "Design a microservices diagram.").await;
let summarizer = SummarizerAgent::new("Writer".into(), "Summarize the architecture decisions.".into());
AutoGPT::default()
.with(agents![architect, summarizer])
.build()
.unwrap()
.run()
.await
.unwrap();
Both run concurrently. If you need sequential ordering, run two separate AutoGPT instances back-to-back.
Using generate vs stream
The AsyncFunctions trait (derived by Auto) exposes two generation methods:
| Method | Return | Use When |
|---|---|---|
self.generate(prompt) | Result<String> | You need the full response as a string |
self.stream(prompt) | Result<ReqResponse> | You want to stream tokens progressively |
self.imagen(prompt) | Result<Vec<u8>> | You need image bytes (requires img feature) |
Working with Task Scope
The task argument carries the Scope configured on AutoGPT:
async fn execute<'a>(&'a mut self, task: &'a mut Task, ...) -> Result<()> {
if let Some(scope) = &task.scope {
if scope.crud {
// write files to disk
}
if scope.external {
// call external APIs
}
}
Ok(())
}
This makes your agent scope-aware and compatible with access control policies at the AutoGPT level.
Complete Working Example
See the gemini-custom-agent example in the repository for a minimal end-to-end Cargo project:
cd examples/gemini-custom-agent
export GEMINI_API_KEY=<your_key>
cargo run --features=gem
Traits Reference
AutoGPT defines a layered set of traits. Understanding them is essential for building custom agents and implementing advanced integrations.
Agent
Defined in autogpt::traits::agent. The base trait every agent must implement. It describes the core state of an agent: its persona, behavior, memory, status, tools, and scheduling.
pub trait Agent: Debug {
fn new(persona: Cow<'static, str>, behavior: Cow<'static, str>) -> Self where Self: Sized;
fn update(&mut self, status: Status);
fn behavior(&self) -> &Cow<'static, str>;
fn persona(&self) -> &Cow<'static, str>;
fn status(&self) -> &Status;
fn memory(&self) -> &Vec<Message>;
fn tools(&self) -> &Vec<Tool>;
fn knowledge(&self) -> &Knowledge;
fn planner(&self) -> Option<&Planner>;
fn profile(&self) -> &Persona;
fn reflection(&self) -> Option<&Reflection>;
fn scheduler(&self) -> Option<&TaskScheduler>;
fn capabilities(&self) -> &HashSet<Capability>;
fn context(&self) -> &ContextManager;
fn tasks(&self) -> &Vec<Task>;
fn memory_mut(&mut self) -> &mut Vec<Message>;
fn planner_mut(&mut self) -> Option<&mut Planner>;
fn context_mut(&mut self) -> &mut ContextManager;
}
The Auto derive macro implements Agent for structs containing an AgentGPT field by forwarding all calls to that field.
Functions
Defined in autogpt::traits::functions. A synchronous accessor trait that provides access to the underlying AgentGPT:
pub trait Functions {
fn get_agent(&self) -> &AgentGPT;
}
AsyncFunctions
Defined in autogpt::traits::functions. The async capability trait. It provides LLM interaction methods:
#[async_trait]
pub trait AsyncFunctions: Send + Sync {
async fn execute<'a>(&'a mut self, task: &'a mut Task, execute: bool, browse: bool, max_tries: u64) -> Result<()>;
// Only available with `mem` feature:
async fn save_ltm(&mut self, message: Message) -> Result<()>;
async fn get_ltm(&self) -> Result<Vec<Message>>;
async fn ltm_context(&self) -> String;
// Only available with an LLM feature (gem, oai, cld, xai, co):
async fn generate(&mut self, request: &str) -> Result<String>;
async fn imagen(&mut self, request: &str) -> Result<Vec<u8>>;
async fn stream(&mut self, request: &str) -> Result<ReqResponse>;
}
Executor
Defined in autogpt::traits::functions. This is the trait you implement in your custom agents. It has one required method:
#[async_trait]
pub trait Executor {
async fn execute<'a>(
&'a mut self,
task: &'a mut Task,
execute: bool,
browse: bool,
max_tries: u64,
) -> Result<()>;
}
AsyncFunctions::execute delegates to your Executor::execute implementation. The key distinction: AsyncFunctions is the trait-object-safe interface used by AutoGPT; Executor is the concrete implementation target for your custom types.
AgentFunctions (Composite)
Defined in autogpt::traits::composite. This supertrait is what agents! and AutoGPT operate on:
pub trait AgentFunctions: Agent + AsyncFunctions + Send + Sync {}
Any type that implements both Agent and AsyncFunctions automatically satisfies AgentFunctions. The Auto derive macro generates this blanket implementation.
Collaborate
Defined in autogpt::traits::functions. Used for networked multi-agent communication (requires net feature):
#[async_trait]
pub trait Collaborate: Send + Sync {
async fn handle_task(&mut self, task: Task) -> Result<()>;
async fn receive_message(&mut self, message: AgentMessage) -> Result<()>;
fn get_id(&self) -> &str;
}
Status Enum
pub enum Status {
Idle,
Active,
Completed,
Error,
}
Agents begin as Idle, transition to Active during execution, and end as either Completed or Error.
The agents! Macro and Auto Derive
AutoGPT provides two procedural-macro utilities that eliminate boilerplate when working with agents.
agents! Macro
Defined in autogpt::macros. Wraps any number of agent values into the Vec<Arc<Mutex<Box<dyn AgentFunctions>>>> type expected by AutoGPT::with:
#[macro_export]
macro_rules! agents {
( $($agent:expr),* $(,)? ) => {
vec![
$(
std::sync::Arc::new(tokio::sync::Mutex::new(
Box::new($agent) as Box<dyn AgentFunctions>
))
),*
]
};
}
Usage
use autogpt::prelude::*;
let a = ArchitectGPT::new("A", "Design a system.").await;
let b = BackendGPT::new("B", "Write REST endpoints.", "rust").await;
// Without the macro, verbose:
let agents_vec: Vec<Arc<Mutex<Box<dyn AgentFunctions>>>> = vec![
Arc::new(Mutex::new(Box::new(a) as Box<dyn AgentFunctions>)),
Arc::new(Mutex::new(Box::new(b) as Box<dyn AgentFunctions>)),
];
// With the macro, concise:
let agents_vec = agents![a, b];
The macro accepts any number of agents and allows a trailing comma.
Auto Derive Macro
Defined in the auto-derive crate (re-exported from autogpt::prelude). Automatically implements Agent, Functions, AsyncFunctions, and AgentFunctions for a struct containing AgentGPT and ClientType fields.
Requirements
Your struct must contain these two fields with these exact types:
pub agent: AgentGPT,
pub client: ClientType,
Any additional fields are ignored by the macro and are freely available for your custom logic.
What It Generates
// These implementations are generated by #[derive(Auto)]:
impl Agent for MyAgent { ... } // forwards to self.agent
impl Functions for MyAgent { ... } // returns &self.agent
impl AsyncFunctions for MyAgent { ... } // LLM generate/stream/imagen + LTM
impl AgentFunctions for MyAgent { ... } // blanket supertrait
The derived AsyncFunctions::execute calls your Executor::execute implementation, bridging the trait-object interface with your custom logic.
Custom Fields in Practice
use autogpt::prelude::*;
#[derive(Debug, Default, Auto)]
pub struct FileWriterAgent {
pub agent: AgentGPT,
pub client: ClientType,
pub output_dir: String, // custom field, available in execute()
}
#[async_trait]
impl Executor for FileWriterAgent {
async fn execute<'a>(
&'a mut self,
_task: &'a mut Task,
_execute: bool,
_browse: bool,
_max_tries: u64,
) -> Result<()> {
let response = self.generate(self.agent.behavior().as_ref()).await?;
let path = format!("{}/output.txt", self.output_dir);
std::fs::write(&path, &response)?;
println!("Wrote {} bytes to {}", response.len(), path);
Ok(())
}
}
IAC Protocol
The IAC (Inter/Intra-Agent Communication) protocol is AutoGPTβs purpose-built communication layer for distributed multi-agent systems. It is the transport backbone of Orchestrated Mode.
Why IAC Exists
Traditional inter-process communication methods, REST, gRPC, bare TCP, suffer under demanding multi-agent workloads:
- TCP + TLS handshake cost: every new connection incurs at least 1 RTT of latency.
- Head-of-line blocking: HTTP/2 multiplexing still stalls when a single packet is lost.
- Token-based authentication: bearer tokens lack cryptographic agent identity and granular revocation.
- Centralized topologies: REST and RPC assume a hub; they have no native peer-to-peer delegation.
IAC addresses all of these with a single coherent protocol.
Transport: QUIC over TLS 1.3
IAC defaults to QUIC (currently implemented as TLS 1.3 over TCP in the Rust implementation, with full QUIC as a roadmap item):
| Property | Benefit |
|---|---|
| 0-RTT reconnection | Reuse prior session parameters for near-instant reconnect |
| Stream multiplexing | Multiple concurrent message streams with no head-of-line blocking |
| Adaptive congestion control | BBR-based pacing keeps throughput smooth at scale |
| Graceful fallback | Degrades to TLS/TCP or UNIX domain sockets when needed |
Cryptographic Agent Identity
Each agent generates an Ed25519 keypair at runtime. The public key is the agentβs identity, it replaces opaque tokens and API keys.
Every IAC message is signed:
- Clone the message and zero the
signaturefield - Serialize via Protocol Buffers
- Sign the serialized bytes with the agentβs Ed25519 private key
- Write the signature bytes back to
signature
The receiver reverses the process to verify. This guarantees unforgeable message provenance, only the private-key holder can produce a valid signature.
Message Format (Protobuf Schema)
syntax = "proto3";
package iac;
enum MessageType {
UNKNOWN = 0;
PING = 1;
BROADCAST = 2;
FILE_TRANSFER = 3;
COMMAND = 4;
DELEGATE_TASK = 5;
}
message Message {
string from = 1; // sender identity (hex public key or alias)
string to = 2; // recipient identity
MessageType msg_type = 3;
string payload_json = 4; // UTF-8 JSON metadata or control object
uint64 timestamp = 5; // microsecond precision
uint64 msg_id = 6; // monotonic counter for deduplication
uint64 session_id = 7; // unique per connection
bytes signature = 8; // Ed25519 signature over the serialized message
bytes extra_data = 9; // binary payload (file chunks, compressed frames)
}
Communication Topologies
| Topology | Description |
|---|---|
| Inter-Agent | Global QUIC mesh; agents broadcast, delegate, or proxy messages to peers |
| Agent-Orchestrator | Hierarchical; orchestrator acts as bootstrap registry and command router |
| Intra-Agent | CPU-local using shared IPC or UNIX domain sockets for minimal-latency pings |
Efficiency Features
Frame compression: zstd is negotiated per session. Dictionary-based compression yields up to 85% payload reduction on repetitive agent messages.
Deduplication: receivers track msg_id and session_id to drop duplicate messages from network retransmissions.
Batching: low-overhead messages are flushed together, reducing per-message overhead.
File transfer: msg_type = FILE_TRANSFER chunks large files with index, total, and checksum metadata in payload_json; raw bytes in extra_data.
Comparison: IAC vs. REST/gRPC
| Feature | REST / gRPC | IAC (TLS/TCP) | IAC (QUIC) |
|---|---|---|---|
| Zero-RTT setup | β | β | β |
| Stream multiplexing | β | β | β (no HOL blocking) |
| Agent identity | API tokens | Bearer tokens | β Ed25519 keypair |
| Mesh / P2P support | β | Partial | β Native delegation |
| Frame compression | β | β | β zstd + dictionaries |
| File transfer | β | β | β Chunked + checksum |
| Dedup / reorder | β | β | β Protocol-level |
SDK: Sending an IAC Message
use autogpt::prelude::*;
async fn send_task(client: &Client, signer: &Signer, to: &str, payload: &str) -> Result<()> {
let mut msg = IacMessage {
from: "my-agent".into(),
to: to.into(),
msg_type: MessageType::DelegateTask,
payload_json: payload.into(),
..Default::default()
};
msg.sign(signer)?;
client.send(msg).await
}
For a complete working example see gemini-iac-client-server.
Orchestrator (orchgpt)
orchgpt is the orchestration binary that manages agent lifecycles, routes IAC commands, and enables rich inter-agent collaboration in Orchestrated Mode. It runs as a standalone long-lived TLS server.
Starting the Orchestrator
orchgpt
By default it binds to 0.0.0.0:8443. Override the address:
export ORCHESTRATOR_ADDRESS=0.0.0.0:9443
orchgpt
The orchestrator will print a confirmation and wait for agent connections.
What the Orchestrator Does
- Listens for inbound TLS connections from
autogptagents on the configured address - Verifies each connecting agentβs Ed25519 public key against its registry
- Routes IAC
Messageframes to the correct registered agent based on thetofield - Manages agent lifecycle, registration, heartbeat, and deregistration
- Broadcasts capability advertisements so agents can discover each other
Connecting Agents
From any terminal (or remote machine), connect an agent:
autogpt --net
Once connected the interactive prompt accepts IAC commands:
/arch create "e-commerce backend" | python
/back create "payment processing API" | rust
/front create "checkout form UI" | javascript
Each command is serialized as an IAC Message with msg_type = create and sent to the orchestrator, which instantiates the appropriate agent.
TLS Certificate Setup
The orchestrator generates ephemeral TLS credentials at startup using the iac-rs crate. No manual certificate provisioning is required for local development.
For production deployments behind a reverse proxy (e.g., nginx, Caddy), terminate TLS at the proxy and point the orchestrator at an internal plaintext address.
Architecture Inside the Orchestrator
βββββββββββββββββββββββββββββββββββββββββββ
β orchgpt process β
β β
β TLS Listener β
β β β
β βββ Agent Registry (HashMap) β
β β βββ ArchitectGPT (id, key) β
β β βββ BackendGPT (id, key) β
β β βββ FrontendGPT (id, key) β
β β β
β βββ Message Router β
β βββ Dispatch by `to` field β
βββββββββββββββββββββββββββββββββββββββββββ
Building the Orchestrator from Source
cd autogpt/autogpt
cargo build --release --features net,cli --bin orchgpt
./target/release/orchgpt
Docker
docker run -it \
-e GEMINI_API_KEY=<key> \
-p 8443:8443 \
--rm --name orchgpt kevinrsdev/orchgpt
π Model Context Protocol (MCP)
AutoGPT has first-class support for the Model Context Protocol (MCP), a universal standard for connecting AI agents to external tools and data sources.
With MCP, you can extend your agents with any MCP-compatible server: filesystem access, database queries, web search, GitHub, Slack, custom APIs, and more.
Requirements
Enable the mcp (and cli) feature flags when building:
cargo run --features "cli,mcp" --bin autogpt
Or install with all features:
cargo install autogpt --all-features
What MCP Servers Can Do
Each MCP server exposes a set of tools the agent can discover and call:
- Stdio servers: Spawned as a child process; communicate over stdin/stdout.
- HTTP servers: Communicate over HTTP/POST with JSON-RPC.
- SSE servers: Server-Sent Events transport.
Quick Overview
| Topic | Page |
|---|---|
| CLI: adding, listing, inspecting, removing | CLI Reference |
| TUI: slash commands inside the interactive shell | TUI Commands |
Environment variables, .env, secrets | Secrets & Env |
| HTTP headers and auth | Auth |
| SDK: programmatic API | SDK Usage |
How It Works
flowchart LR
CLI["autogpt\nmcp add"] --> Settings["~/.autogpt/settings.json"]
Settings --> McpManager["McpManager\n(discovery)"]
McpManager --> StdioTransport["Stdio Transport\n(subprocess)"]
McpManager --> HttpTransport["HTTP Transport\n(POST JSON-RPC)"]
McpManager --> Agent["Agent / TUI\n(tool dispatch)"]
Agent --> Tool["Tool Result"]
- You register servers via the CLI or TUI.
- Settings are stored in
~/.autogpt/settings.json. - On connect, the
McpManagerspawns/connects and runstools/list. - Discovered tools are prefixed as
mcp_{server}_{tool}to avoid collisions. - Agents or the TUI can call any tool via
mcp call.
The settings.json MCP Block
MCP server configurations live under the mcp key in ~/.autogpt/settings.json:
{
"mcp": {
"my-server": {
"name": "my-server",
"transport": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-everything"],
"env": {
"API_KEY": "$MY_API_TOKEN"
},
"headers": {},
"timeout_ms": 30000,
"trust": false,
"include_tools": [],
"exclude_tools": []
}
}
}
Never hard-code secrets. Use
$VAR,${VAR}, or%VAR%references inenvandheadersvalues. They are expanded at runtime from your shell environment or.envfile. See Secrets & Env.
Field Reference
| Field | Type | Default | Description |
|---|---|---|---|
transport | string | stdio | stdio, http, or sse |
command | string | - | Path or name of executable (stdio) or base URL (http/sse) |
args | string[] | [] | Arguments passed to the executable (stdio only) |
env | object | {} | Environment variables; values support $VAR, ${VAR}, %VAR% |
headers | object | {} | HTTP headers for http/sse transports; values support env expansion |
timeout_ms | number | 30000 | Connection + request timeout in ms |
trust | bool | false | When true, skip all tool-call confirmations |
include_tools | string[] | [] | If non-empty, only these tools are exposed (allowlist) |
exclude_tools | string[] | [] | Tools to hide even if exposed by the server (blocklist, takes precedence) |
description | string | "" | Human-readable label shown in list and inspect |
Examples
Public npm MCP server (stdio)
autogpt mcp add everything --command npx -- -y @modelcontextprotocol/server-everything
Add a GitHub MCP server via Docker (Stdio)
autogpt mcp add github --transport stdio --command 'docker' --args 'run,-i,ghcr.io/modelcontextprotocol/servers/github:latest' --env 'GITHUB_TOKEN=$TOKEN'
Add a search server via SSE
autogpt mcp add search --transport sse --url 'https://search.wiseai.dev/mcp/sse' --header 'Authorization: Bearer $MY_API_KEY'
Note: Make sure your environment variables (e.g.,
$TOKEN,$MY_API_KEY) are exported in your shell before running these commands, as they are expanded by your shell before being passed to AutoGPT.
Filtered tool exposure
autogpt mcp add secure-server \
--command npx -- -y @modelcontextprotocol/server-everything \
--include-tools echo,add \
--exclude-tools get-env
See Also
MCP CLI Reference
The autogpt mcp command family lets you manage MCP server configurations from your terminal without editing settings.json by hand.
autogpt mcp add
Register a new MCP server.
autogpt mcp add [OPTIONS] <NAME> [-- <SERVER_ARGS>...]
| Option | Short | Description |
|---|---|---|
--command <CMD> | -c | Executable path (stdio) or endpoint URL (http/sse) |
--transport <TYPE> | -t | stdio (default), http, or sse |
--env <KEY=VALUE> | -e | Environment variable (repeatable) |
--header <KEY: VALUE> | -H | HTTP header (repeatable, http/sse only) |
--timeout <MS> | Connection timeout in milliseconds (default: 30000) | |
--trust | Bypass tool-call confirmation prompts for this server | |
--description <TEXT> | Human-readable label shown in list and inspect | |
--include-tools <...> | Comma-separated allowlist of tool names | |
--exclude-tools <...> | Comma-separated blocklist of tool names |
Adding a stdio server
autogpt mcp add everything --command npx -- -y @modelcontextprotocol/server-everything
Adding a stdio server with environment variables
Values are stored as-is in settings.json; they are expanded from the shell or .env at runtime:
autogpt mcp add github \
--command npx -- -y @modelcontextprotocol/server-github \
--env 'GITHUB_TOKEN=${GITHUB_TOKEN}'
Adding an HTTP server
autogpt mcp add my-api \
--transport http \
--command https://api.wiseai.dev/mcp \
--timeout 10000
Adding an HTTP server with an auth header
autogpt mcp add secure-api \
--transport http \
--command https://api.wiseai.dev/mcp \
--header 'Authorization: Bearer $MY_API_TOKEN'
Adding an SSE server
autogpt mcp add sse-stream \
--transport sse \
--command https://wiseai.dev/mcp/sse \
--header 'X-Api-Key: $STREAM_KEY'
Filtering exposed tools
autogpt mcp add safe-server \
--command npx -- -y @modelcontextprotocol/server-everything \
--include-tools echo,add \
--trust
autogpt mcp list
Show all configured servers with their live connection status.
autogpt mcp list
autogpt mcp inspect <NAME>
Show detailed information and all available tools for a specific server.
autogpt mcp inspect everything
Example output:
βΈ MCP Server: everything
Transport: stdio
Connection: npx -y @modelcontextprotocol/server-everything
Status: CONNECTED
Trust: no
Timeout: 30000ms
βΈ Available Tools (13):
echo Echoes back the input string
* message: string - Message to echo
get-annotated-message Demonstrates how annotations can be used to provide metadata about content.
includeImage: boolean - Whether to include an example image
* messageType: string - Type of message to demonstrate different annotation patterns
get-env Returns all environment variables, helpful for debugging MCP server configuration
get-resource-links Returns up to ten resource links that reference different types of resources
count: number - Number of resource links to return (1-10)
get-resource-reference Returns a resource reference that can be used by MCP clients
resourceId: number - ID of the text resource to fetch
resourceType: string -
get-structured-content Returns structured content along with an output schema for client data validation
* location: string - Choose city
get-sum Returns the sum of two numbers
* b: number - Second number
* a: number - First number
get-tiny-image Returns a tiny MCP logo image.
gzip-file-as-resource Compresses a single file using gzip compression. Depending upon the selected output type, returns either the compressed data as a gzipped resource or a resource link, allowing it to be downloaded in a subsequent request during the current session.
name: string - Name of the output file
outputType: string - How the resulting gzipped file should be returned. 'resourceLink' returns a link to a resource that can be read later, 'resource' returns a full resource object.
data: string - URL or data URI of the file content to compress
toggle-simulated-logging Toggles simulated, random-leveled logging on or off.
toggle-subscriber-updates Toggles simulated resource subscription updates on or off.
trigger-long-running-operation Demonstrates a long running operation with progress updates.
steps: number - Number of steps in the operation
duration: number - Duration of the operation in seconds
simulate-research-query Simulates a deep research operation that gathers, analyzes, and synthesizes information. Demonstrates MCP task-based operations with progress through multiple stages. If 'ambiguous' is true and client supports elicitation, sends an elicitation request for clarification.
ambiguous: boolean - Simulate an ambiguous query that requires clarification (triggers input_required status)
* topic: string - The research topic to investigate
autogpt mcp call <SERVER> <TOOL> [ARGS...]
Manually invoke a tool on a registered MCP server. Useful for testing and debugging.
autogpt mcp call <SERVER> <TOOL> [ARGS...]
Arguments can be passed as key=value pairs or as a JSON string.
Calling with key=value pairs
autogpt mcp call everything echo message="Hello, World"
Echo: Hello, World
Calling with a JSON argument string
autogpt mcp call everything get-sum '{"a": 5, "b": 3}'
The sum of 5 and 3 is 8.
Calling a tool with no arguments
autogpt mcp call everything get-env
Example output:
{
"CARGO_PKG_NAME": "autogpt",
"CARGO_PKG_DESCRIPTION": "π¦ A Pure Rust Framework For Building AGIs.\n",
"EDITOR": "vim"
}
autogpt mcp remove <NAME>
Permanently remove a server from settings.json.
autogpt mcp remove everything
Output:
β MCP server 'everything' removed.
Settings Storage
All configurations are stored in ~/.autogpt/settings.json. You can edit this file directly if needed; the CLI is a convenience wrapper.
{
"mcp": {
"everything": {
"name": "everything",
"transport": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-everything"],
"env": {},
"headers": {},
"timeout_ms": 30000,
"trust": false,
"include_tools": [],
"exclude_tools": [],
"description": "Everything test server"
}
}
}
MCP TUI Commands
The interactive AutoGPT shell (autogpt with no arguments) exposes all MCP management commands as TUI slash commands. These work identically to the CLI equivalents but without leaving the shell.
Slash Command Reference
| Command | Description |
|---|---|
/mcp list | List all servers and their status |
/mcp inspect <name> | Show tools and config for one server |
/mcp remove <name> | Remove a server from settings |
/mcp call <server> <tool> [args...] | Manually invoke a tool |
Type
/helpinside the shell to see all available commands, including MCP ones.
/mcp list
Show all registered MCP servers and whether they are reachable.
> /mcp list
/mcp inspect <name>
Display detailed information about a single server, including all discovered tools.
> /mcp inspect everything
Output:
βΈ MCP Server: everything
Transport: stdio
Connection: npx -y @modelcontextprotocol/server-everything
Status: CONNECTED
Trust: no
Timeout: 10000ms
βΈ Available Tools (13):
echo Echoes back the input string
* message: string - Message to echo
get-annotated-message Demonstrates how annotations can be used to provide metadata about content.
* messageType: string - Type of message to demonstrate different annotation patterns
includeImage: boolean - Whether to include an example image
get-env Returns all environment variables, helpful for debugging MCP server configuration
get-resource-links Returns up to ten resource links that reference different types of resources
count: number - Number of resource links to return (1-10)
get-resource-reference Returns a resource reference that can be used by MCP clients
resourceId: number - ID of the text resource to fetch
resourceType: string -
get-structured-content Returns structured content along with an output schema for client data validation
* location: string - Choose city
get-sum Returns the sum of two numbers
* b: number - Second number
* a: number - First number
get-tiny-image Returns a tiny MCP logo image.
gzip-file-as-resource Compresses a single file using gzip compression. Depending upon the selected output type, returns either the compressed data as a gzipped resource or a resource link, allowing it to be downloaded in a subsequent request during the current session.
name: string - Name of the output file
outputType: string - How the resulting gzipped file should be returned. 'resourceLink' returns a link to a resource that can be read later, 'resource' returns a full resource object.
data: string - URL or data URI of the file content to compress
toggle-simulated-logging Toggles simulated, random-leveled logging on or off.
toggle-subscriber-updates Toggles simulated resource subscription updates on or off.
trigger-long-running-operation Demonstrates a long running operation with progress updates.
duration: number - Duration of the operation in seconds
steps: number - Number of steps in the operation
simulate-research-query Simulates a deep research operation that gathers, analyzes, and synthesizes information. Demonstrates MCP task-based operations with progress through multiple stages. If 'ambiguous' is true and client supports elicitation, sends an elicitation request for clarification.
ambiguous: boolean - Simulate an ambiguous query that requires clarification (triggers input_required status)
* topic: string - The research topic to investigate
/mcp call <server> <tool> [args...]
Invoke any tool directly from the shell. This is useful for testing and debugging your server configuration without going through the agent.
Arguments can be passed as key=value pairs:
> /mcp call everything echo message="Hello from the TUI!"
Or as a raw JSON object:
> /mcp call everything get-sum '{"a": 10, "b": 32}'
Example output:
β Tool 'get-sum' called successfully on 'everything'
The sum of 10 and 32 is 42.
Calling a no-argument tool:
> /mcp call everything get-env
/mcp remove <name>
Remove a server from the configuration. The change is persisted to ~/.autogpt/settings.json immediately.
> /mcp remove everything
β MCP server 'everything' removed.
Adding Servers from the TUI
Server registration is a CLI-only operation (it requires flag-based input). Add servers with the autogpt mcp add CLI command before starting the shell, or in a separate terminal while the shell is running.
Changes to ~/.autogpt/settings.json are picked up on the next /mcp list or /mcp inspect call.
Getting Help
> /help
Output:
MCP Commands
/mcp list Show all configured MCP servers and their status
/mcp inspect <name> Inspect a server and list its tools
/mcp remove <name> Remove a server registration
/mcp call <srv> <tool> [args] Call an MCP tool with JSON args or key=val pairs
Secrets, Environment Variables & .env Files
AutoGPTβs MCP integration is designed so that no raw secrets are ever stored in settings.json. Instead, use variable references that are resolved at runtime.
Variable Expansion
All values in the env and headers blocks of an MCP server config support three expansion syntaxes:
| Syntax | Platform | Example |
|---|---|---|
$VAR | All | $MY_API_KEY |
${VAR} | All | ${MY_API_KEY} |
%VAR% | Windows | %MY_API_KEY% |
If the referenced variable is not set, it expands to an empty string.
Example: env block
{
"mcp": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}",
"LOG_LEVEL": "$LOG_LEVEL"
}
}
}
}
When autogpt spawns the server, it replaces ${GITHUB_TOKEN} with the actual value from your shell environment (or .env file) before passing it to the subprocess.
Example: headers block
HTTP and SSE transports support the same expansion in header values:
{
"mcp": {
"my-api": {
"transport": "http",
"command": "https://api.wiseai.dev/mcp",
"headers": {
"Authorization": "Bearer $MY_API_TOKEN"
}
}
}
}
Adding via CLI (keeps references intact)
The CLI preserves the literal reference string in settings.json:
autogpt mcp add github \
--command npx -- -y @modelcontextprotocol/server-github \
--env "GITHUB_TOKEN=${GITHUB_TOKEN}"
autogpt mcp add my-api \
--transport http \
--command https://api.wiseai.dev/mcp \
--header "Authorization: Bearer $MY_API_TOKEN"
The single quotes in shell commands prevent premature expansion by your terminal. The literal string
$MY_API_TOKENis stored insettings.jsonand expanded when autogpt runs.
.env File Support
autogpt automatically loads .env files on startup. Variables from .env are set in the process environment only if they are not already set, so your shell environment always takes precedence.
Lookup order
.envin the current working directory$HOME/.env(home directory)$HOME/.autogpt/.env(autogpt config directory)
.env file format
GITHUB_TOKEN=ghp_...
MY_API_KEY=sk-...
LOG_LEVEL=info
Quoted values are unquoted automatically:
DATABASE_URL="postgresql://user:pass@localhost/db"
GREETING='hello world'
Workflow example
Create a .env file in your project root:
echo 'MY_API_TOKEN=sk-abc123' >> .env
echo 'GITHUB_TOKEN=ghp_xyz' >> .env
Register your servers using references:
autogpt mcp add my-api \
--transport http \
--command https://api.wiseai.dev/mcp \
--header "Authorization: Bearer $MY_API_TOKEN"
The stored settings.json will contain:
"headers": {
"Authorization": "Bearer $MY_API_TOKEN"
}
When you next run autogpt, it loads .env, sets MY_API_TOKEN, and the header is expanded before the HTTP request is sent.
Security Redaction Policy
By default, AutoGPT applies a security redaction filter when spawning MCP stdio subprocesses. This prevents third-party servers from accidentally inheriting sensitive secrets from your shell.
What gets redacted
Environment variables whose names match any of the following patterns are removed from the inherited environment before the server process is started:
| Pattern | Examples |
|---|---|
*API_KEY* | GEMINI_API_KEY, OPENAI_API_KEY |
*TOKEN* | GITHUB_TOKEN, OAUTH_ACCESS_TOKEN |
*SECRET* | AWS_SECRET_ACCESS_KEY, JWT_SECRET |
*PASSWORD* | DB_PASSWORD, REDIS_PASSWORD |
*AUTH* | BEARER_AUTH, X_AUTH_HEADER |
*CREDENTIAL* | GOOGLE_CREDENTIALS, AZURE_CREDENTIALS |
GOOGLE_APPLICATION_CREDENTIALS (exact) | - |
Explicit overrides bypass redaction
Variables you explicitly list in the env block of a server config are always passed through, even if their name matches a redaction pattern. This follows the principle of informed consent: if you deliberately configure a variable for a server, it is trusted.
"env": {
"OPENAI_API_KEY": "$OPENAI_API_KEY"
}
This is the only safe way to pass a secret to an MCP server.
Verification example
You can verify which variables actually reach a server using the get-env tool from @modelcontextprotocol/server-everything:
autogpt mcp add test-server \
--command npx -- -y @modelcontextprotocol/server-everything \
--env "MY_KEY=${MY_SECRET}"
autogpt mcp call test-server get-env
You should see MY_KEY in the output (expanded), but not MY_SECRET directly as an inherited variable.
Summary
| Concern | Recommendation |
|---|---|
| Storing secrets | Never, use $VAR references |
| Loading secrets at runtime | Shell env or .env files |
| Passing secrets to a server | Only via env block with "KEY": "$VAR" pattern |
| Protecting inherited secrets | Automatic, redaction policy removes them by default |
MCP Authentication
AutoGPT supports authentication for both stdio (via environment variables) and HTTP/SSE (via custom headers) MCP servers.
Stdio Servers: Environment Variables
Stdio-based MCP servers receive secrets through their environment. Pass them using the --env flag or the env block in settings.json. Use variable references to keep raw values out of your config file.
autogpt mcp add github \
--command npx -- -y @modelcontextprotocol/server-github \
--env 'GITHUB_TOKEN=${GITHUB_TOKEN}'
The resulting settings.json entry:
"mcp": {
"github": {
"name": "github",
"transport": "stdio",
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-github",
"--env",
"GITHUB_TOKEN=${GITHUB_TOKEN}"
],
"timeout_ms": 30000,
"trust": false
}
}
${GITHUB_TOKEN} is expanded at spawn time from your shell environment or .env file. See Secrets & Env β.
HTTP/SSE Servers: Custom Headers
HTTP and SSE transports support arbitrary HTTP headers. This is the standard mechanism for passing Authorization, API keys, or tenant IDs to remote MCP servers.
Bearer Token
autogpt mcp add secure-api \
--transport http \
--command https://api.wiseai.dev/mcp \
--header 'Authorization: Bearer $MY_API_TOKEN'
settings.json:
"headers": {
"Authorization": "Bearer $MY_API_TOKEN"
}
The header value is expanded before each HTTP request.
API Key in a custom header
autogpt mcp add analytics \
--transport http \
--command https://analytics.wiseai.dev/mcp \
--header 'X-Api-Key: $ANALYTICS_KEY'
Multiple headers
Repeat --header for each header:
autogpt mcp add multi-auth \
--transport http \
--command https://api.wiseai.dev/mcp \
--header 'Authorization: Bearer $TOKEN' \
--header 'X-Tenant-ID: ${TENANT_ID}' \
--header "Content-Type: application/json"
Verifying Authentication
Use autogpt mcp inspect to check whether the server accepted the auth:
autogpt mcp inspect secure-api
Security Notes
- Never hard-code tokens in
settings.json. Always use$VARor${VAR}. - Store secrets in your shell profile, CI/CD secret manager, or a
.envfile that is listed in.gitignore. - HTTP headers are transmitted in plain text. Use
https://endpoints whenever passing auth headers to remote servers. - For stdio servers, the redaction policy prevents other inherited secrets from leaking into the subprocess.
MCP SDK Usage
In addition to the CLI and TUI, you can interact with MCP programmatically from Rust using the McpClient, McpManager, and settings types directly.
Feature Flag
# Cargo.toml
[dependencies]
autogpt = { version = "0.4.5", features = ["mcp"] }
Core Types
| Type | Location | Purpose |
|---|---|---|
McpServerConfig | autogpt::mcp::settings | Single server configuration |
McpTransport | autogpt::mcp::settings | Transport enum: Stdio, Http, Sse |
McpClient | autogpt::mcp::client | Low-level client for one server |
McpManager | autogpt::mcp::manager | High-level manager for multiple servers |
McpTool | autogpt::mcp::types | Discovered tool descriptor |
McpServerInfo | autogpt::mcp::types | Connection status + tool list |
SettingsManager | autogpt::cli::settings | Read/write ~/.autogpt/settings.json |
McpClient: Connecting to a Single Server
McpClient manages the lifecycle for one MCP server: connect, discover tools, call tools.
Stdio server
use autogpt::prelude::*;
use std::collections::HashMap;
fn main() -> Result<()> {
let config = McpServerConfig {
name: "everything".into(),
transport: McpTransport::Stdio,
command: Some("npx".into()),
args: vec!["-y".into(), "@modelcontextprotocol/server-everything".into()],
env: HashMap::new(),
headers: HashMap::new(),
timeout_ms: 30_000,
trust: true,
..Default::default()
};
let mut client = McpClient::new("everything");
client.connect(&config)?;
let info = client.to_server_info("Everything test server");
println!("Status: {:?}", info.status);
for tool in &info.tools {
println!(" {} - {}", tool.name, tool.description);
}
let mut args = HashMap::new();
args.insert("message".into(), serde_json::json!("hello"));
let result = client.call_tool("echo", args)?;
println!("{}", serde_json::to_string_pretty(&result)?);
Ok(())
}
// Status: Connected
// echo - Echoes back the input string
// get-annotated-message - Demonstrates how annotations can be used to provide metadata about content.
// get-env - Returns all environment variables, helpful for debugging MCP server configuration
// get-resource-links - Returns up to ten resource links that reference different types of resources
// get-resource-reference - Returns a resource reference that can be used by MCP clients
// get-structured-content - Returns structured content along with an output schema for client data validation
// get-sum - Returns the sum of two numbers
// get-tiny-image - Returns a tiny MCP logo image.
// gzip-file-as-resource - Compresses a single file using gzip compression. Depending upon the selected output type, returns either the compressed data as a gzipped resource or a resource link, allowing it to be downloaded in a subsequent request during the current session.
// toggle-simulated-logging - Toggles simulated, random-leveled logging on or off.
// toggle-subscriber-updates - Toggles simulated resource subscription updates on or off.
// trigger-long-running-operation - Demonstrates a long running operation with progress updates.
// simulate-research-query - Simulates a deep research operation that gathers, analyzes, and synthesizes information. Demonstrates MCP task-based operations with progress through multiple stages. If 'ambiguous' is true and client supports elicitation, sends an elicitation request for clarification.
// {
// "success": true,
// "content": "Echo: hello",
// "data": null,
// "error": null
// }
HTTP server with auth header
use autogpt::prelude::*;
use std::collections::HashMap;
let mut headers = HashMap::new();
headers.insert(
"Authorization".into(),
"Bearer my-secret-token".into(), // or "$MY_TOKEN" for expansion
);
let config = McpServerConfig {
name: "secure-api".into(),
transport: McpTransport::Http,
http_url: Some("https://api.wiseai.dev/mcp".into()),
headers,
timeout_ms: 10_000,
..Default::default()
};
Filtering tools
let config = McpServerConfig {
name: "filtered".into(),
transport: McpTransport::Stdio,
command: Some("npx".into()),
args: vec!["-y".into(), "@modelcontextprotocol/server-everything".into()],
include_tools: vec!["echo".into(), "add".into()],
exclude_tools: vec!["get-env".into()],
..Default::default()
};
McpManager: Managing Multiple Servers
McpManager connects to all configured servers at once and provides a unified tool dispatch interface. This is what agents use internally.
use autogpt::prelude::*;
use std::collections::HashMap;
let mut servers: HashMap<String, McpServerConfig> = HashMap::new();
servers.insert("everything".into(), McpServerConfig {
name: "everything".into(),
transport: autogpt::mcp::settings::McpTransport::Stdio,
command: Some("npx".into()),
args: vec!["-y".into(), "@modelcontextprotocol/server-everything".into()],
trust: true,
..Default::default()
});
let mut mgr = McpManager::new(servers, vec![], vec![]);
mgr.connect_all();
for info in mgr.server_infos() {
println!("Server: {}", info.name);
for tool in info.tools {
println!(" {}", tool.fqn); // e.g. "mcp_everything_echo"
}
}
let mut args = HashMap::new();
args.insert("message".into(), serde_json::json!("hello from sdk"));
let result = mgr.call_tool("mcp_everything_echo", args).await?;
println!("{}", serde_json::to_string_pretty(&result)?);
Tool FQN Naming Convention
Every discovered tool is assigned a Fully Qualified Name (FQN) to avoid collisions across servers:
mcp_{server_name}_{tool_name}
Non-alphanumeric characters (except -) are replaced with _. Examples:
| Server name | Tool name | FQN |
|---|---|---|
everything | echo | mcp_everything_echo |
my-api | query-data | mcp_my-api_query-data |
github | create_issue | mcp_github_create_issue |
SettingsManager: Read/Write Config Programmatically
use autogpt::prelude::*;
// Load from default path (~/.autogpt/settings.json)
let mgr = SettingsManager::new();
let config = McpServerConfig {
name: "my-server".into(),
transport: McpTransport::Stdio,
command: Some("npx".into()),
args: vec!["-y".into(), "@modelcontextprotocol/server-everything".into()],
description: Some("Test server".into()),
..Default::default()
};
mgr.add_mcp_server(config)?;
let settings = mgr.load()?;
for (name, cfg) in &settings.mcp {
println!("{}: {:?}", name, cfg.transport);
}
let (_, existed) = mgr.remove_mcp_server("my-server")?;
assert!(existed);
Examples
Full working examples are available in the repository:
| Example | Description |
|---|---|
mcp-server-registration | Register MCP servers on an agent |
mcp-manager | Direct use of McpManager |
mcp-custom-agent | Custom agent with pre-loaded MCP tools |
Long-Term Memory (Pinecone)
AutoGPT can persist agent conversation history to a Pinecone vector database, giving agents durable memory across separate runs. This enables agents that learn from prior interactions, recall past decisions, and improve over time.
Enabling Long-Term Memory
Add the mem feature flag:
[dependencies]
autogpt = { version = "0.4.1", features = ["gem", "gpt", "mem"] }
Set the Pinecone environment variables:
export PINECONE_API_KEY=<your_pinecone_api_key>
export PINECONE_INDEX_URL=<your_pinecone_index_url>
The index URL has the form https://<index-name>-<project-id>.svc.<region>.pinecone.io.
Follow the Pinecone setup guide for step-by-step index creation instructions.
How It Works
When a mem-enabled agent runs, after each LLM response it automatically calls save_ltm to upsert the message into Pinecone as a vector embedding. On subsequent runs, get_ltm retrieves the most semantically relevant prior messages and prepends them to the conversation context.
API Reference
save_ltm
async fn save_ltm(&mut self, message: Message) -> Result<()>
Upserts a Message into the Pinecone index. Called automatically by built-in agents; call manually in custom Executor implementations:
self.save_ltm(Message {
role: "assistant".into(),
content: response.clone().into(),
}).await?;
get_ltm
async fn get_ltm(&self) -> Result<Vec<Message>>
Retrieves all stored messages for this agent from Pinecone.
ltm_context
async fn ltm_context(&self) -> String
Returns all stored messages formatted as "role: content\n", ready to be prepended to a new prompt.
Inspecting Memory After a Run
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let agent = ArchitectGPT::new("Architect", "Design a Kubernetes cluster.").await;
let autogpt = AutoGPT::default()
.with(agents![agent])
.build()
.unwrap();
autogpt.run().await.unwrap();
let guard = autogpt.agents[0].lock().await;
let state = guard.get_agent();
println!("In-memory messages: {}", state.memory().len());
println!("First role: {}", state.memory()[0].role);
println!("Second role: {}", state.memory()[1].role);
println!("Status: {:?}", state.status());
}
Expected output when memory is populated:
All agents executed successfully.
In-memory messages: 3
First role: user
Second role: assistant
Status: Completed
π€ Collaborative Multi-Provider Agents (col)
The col feature adds [CollabPool]: a provider routing registry that enables AutoGPT to execute agents sequentially across multiple LLM providers in round-robin order.
Overview
flowchart TD
A["π€ User Prompt"] --> B["π€ AutoGPT"]
B --> C{"CollabPool picks start"}
C -->|"Random"| D["Provider A agents![0]"]
C -->|"Explicit(name)"| D
D --> E["Provider B agents![1]"]
E --> F["Provider C agents![2]"]
F --> G["β
Execution Complete"]
- Library usage (
colonly):CollabPool::from_providers(names): pure routing, no API keys required at build time. - CLI/TUI usage (
col + cli):CollabPool::from_env(): auto-discovers all providers with API keys set, spawns oneGenericAgentper provider.
SDK Usage
Enable the feature in Cargo.toml:
[dependencies]
autogpt = { version = "0.4.5", features = ["col", "gem"] }
All collab types are available via the prelude:
use autogpt::prelude::*; // imports CollabPool, CollabSelection
CollabPool::from_providers
Build a lightweight routing pool from a list of provider names: no agents or API keys required:
let pool = CollabPool::from_providers(vec![
"gemini".to_string(),
"openai".to_string(),
"anthropic".to_string(),
]);
println!("{} providers", pool.len());
println!("start at: {}", pool.provider_name(pool.pick_start(&CollabSelection::Random)));
Attaching a Pool to AutoGPT
Pass the pool to AutoGPT::with_collab_pool(). The orchestrator uses the pool to determine execution order when run() is called:
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let pool = CollabPool::from_providers(vec![
"gemini".to_string(),
"openai".to_string(),
]);
let agent_a = ArchitectGPT::new("Architect", "Design a task management system.").await;
let agent_b = ArchitectGPT::new("Architect", "Design a task management system.").await;
let autogpt = AutoGPT::default()
.with(agents![agent_a, agent_b])
.with_collab_pool(pool)
.build()
.expect("Failed to build AutoGPT");
autogpt.run().await.unwrap();
}
CollabSelection
| Variant | Behaviour |
|---|---|
CollabSelection::Random | Picks a random start index |
CollabSelection::Explicit(name) | Always starts from the named provider |
API Reference
| Method | Description |
|---|---|
CollabPool::from_providers(names) | Build a routing pool from provider name strings |
pool.len() | Number of providers in the pool |
pool.is_empty() | true if no providers registered |
pool.provider_name(idx) | Name of the provider at index idx |
pool.pick_start(selection) | Returns starting index per CollabSelection |
AutoGPT::with_collab_pool(pool) | Attach the pool to the orchestrator |
CLI / TUI Collab Mode (col + cli)
Enable collab in the TUI binary:
cargo run --features "cli,col,gem,oai,xai" --bin autogpt -- --collab
from_env() automatically discovers all providers whose API key is set:
| Provider | Env Var |
|---|---|
| Gemini | GEMINI_API_KEY |
| OpenAI | OPENAI_API_KEY |
| Anthropic | ANTHROPIC_API_KEY |
| XAI | XAI_API_KEY |
| Cohere | COHERE_API_KEY |
| HuggingFace | HF_API_KEY |
Fallback Behaviour
When a provider fails, the pool automatically falls back:
| Event | Action |
|---|---|
| Rate-limit / quota / 401 / 402 error | Rotate to providerβs next model and retry |
| All models for provider exhausted | Remove provider; route to next available provider |
| All providers exhausted | Log β All collab providers exhausted. |
The TUI shows π€ (start), π (fallback), and β (exhausted) log prefixes.
See Also
π§ Agent Metacognition (mta)
The mta feature embeds a [MetacognitionEngine] inside every [AgentGPT]. It records task outcomes, generates per-task insights, and injects a strategy context string into subsequent LLM prompts, enabling agents to self-correct based on past performance.
Overview
flowchart TD
A["π Task Outcome Recorded record_task_outcome(task, outcome, retries)"] --> B["π§ MetacognitionEngine generates insight + optional strategy adjustment"]
B --> C{"Should adjust strategy?"}
C -->|"Yes (2+ failures or every 3 tasks)"| D["π Strategy Adjustment injected via metacognition_context()"]
C -->|"No"| E["π Insight stored in MetacognitionEntry"]
D --> F["π¬ Next LLM Prompt enriched with strategy context"]
E --> F
In the TUI/CLI (
GenericAgent), the engine fires automatically every 3 tasks or after 2+ consecutive failures. The TUI status bar shows MetaCognizing during this phase.
SDK Usage
Enable the feature in Cargo.toml:
[dependencies]
autogpt = { version = "0.4.5", features = ["mta", "gem"] }
All metacognition types are available via the prelude:
use autogpt::prelude::*; // imports MetacognitionEngine, MetacognitionEntry
Recording Task Outcomes
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let mut agent = AgentGPT::new_borrowed("Research Analyst", "Summarise papers.");
// Record task outcomes. Returns a MetacognitionEntry with insight + optional strategy.
let entry = agent.record_task_outcome("parse pdf", "success", 0);
println!("Insight: {}", entry.insight);
let entry = agent.record_task_outcome("extract methodology", "failed", 2);
println!("Insight : {}", entry.insight);
if let Some(adj) = &entry.strategy_adjustment {
println!("Strategy: {adj}");
}
// Check aggregate state.
println!("Should adjust? {}", agent.should_adjust_strategy());
println!("Consecutive failures: {}", agent.consecutive_failures());
// The full context string injected into the next LLM prompt.
println!("{}", agent.metacognition_context());
}
API Reference
| Method | Returns | Description |
|---|---|---|
agent.record_task_outcome(task, outcome, retries) | MetacognitionEntry | Record and analyse a task result |
agent.metacognition_context() | String | LLM-injectable strategy context string |
agent.should_adjust_strategy() | bool | true when engine recommends a change |
agent.consecutive_failures() | u32 | Count of consecutive failing tasks |
MetacognitionEntry
pub struct MetacognitionEntry {
pub task: String,
pub outcome: String, // "success" | "failed"
pub retries: u8,
pub insight: String, // generated by the engine
pub strategy_adjustment: Option<String>,
}
GenericAgent Integration (mta + cli)
When both mta and cli features are enabled, GenericAgent triggers metacognition automatically during the task reflection phase:
cargo run --features "cli,mta,gem" --bin autogpt
Trigger conditions (any one):
- Every 3 completed tasks.
- After 2+ consecutive failures.
When triggered, the agent sends a structured metacognition prompt to the LLM to derive strategy adjustments for remaining tasks. The TUI status bar transitions to MetaCognizing during this phase, then reverts to Working when complete.
Running with AutoGPT
Metacognition data is recorded on the AgentGPT level and is available after AutoGPT::run() completes if you hold a reference to the agent:
use autogpt::prelude::*;
#[tokio::main]
async fn main() {
let persona = "Research Analyst";
let behavior = "Summarise and extract insights from research papers.";
// Seed metacognition before run.
let mut probe = AgentGPT::new_borrowed(persona, behavior);
probe.record_task_outcome("previous task", "failed", 1);
println!("Context: {}", probe.metacognition_context());
let agent = ArchitectGPT::new(persona, behavior).await;
AutoGPT::default()
.with(agents![agent])
.build()
.expect("Failed to build AutoGPT")
.run()
.await
.unwrap();
}
See Also
Feature Flags
AutoGPTβs Cargo.toml uses feature flags to keep the binary lean. Only compile what you need. Features are additive: enable multiple with a comma-separated list.
Full Feature Table
| Feature | Enables | Required Env Vars |
|---|---|---|
gem | Gemini LLM client (gems crate) | GEMINI_API_KEY |
oai | OpenAI client (openai_dive crate) | OPENAI_API_KEY |
cld | Anthropic Claude client | ANTHROPIC_API_KEY |
xai | XAI Grok client (x-ai crate) | XAI_API_KEY |
co | Cohere client (cohere-rust crate) | COHERE_API_KEY |
hf | HuggingFace client (api_huggingface crate) | HF_API_KEY |
mcp | Model Context Protocol (MCP) support | N/A |
gpt | All built-in GPT agents (ManagerGPT, ArchitectGPT, BackendGPT, FrontendGPT, OptimizerGPT) | One LLM feature |
img | DesignerGPT image generation (getimg crate) | GETIMG_API_KEY |
git | GitGPT auto-commit (git2 crate) | Git repo in workspace |
mail | MailerGPT email integration (nylas crate) | NYLAS_* vars |
mem | Pinecone long-term memory (pinecone-sdk crate) | PINECONE_API_KEY, PINECONE_INDEX_URL |
net | IAC protocol networking (iac-rs crate) | ORCHESTRATOR_ADDRESS |
cli | Interactive shell, session mgmt, YAML/TOML parsing, terminal UI | One LLM feature |
Common Combinations
Minimal SDK, Gemini only:
autogpt = { version = "0.4.5", features = ["gem", "gpt"] }
Full CLI with Gemini:
autogpt = { version = "0.4.5", features = ["gem", "gpt", "cli"] }
SDK with memory:
autogpt = { version = "0.4.5", features = ["gem", "gpt", "mem"] }
Networked orchestrated mode:
autogpt = { version = "0.4.5", features = ["gem", "gpt", "net", "cli"] }
Everything:
autogpt = { version = "0.4.5", features = ["gem", "gpt", "img", "git", "mail", "mem", "net", "cli"] }
Or equivalently from the command line:
cargo install autogpt --all-features
Compile-Time Feature Guards
In the source code, all feature-gated APIs are guarded with #[cfg(feature = "...")]. If you call DesignerGPT::new without the img feature, compilation fails with a clear #[cfg] error rather than a runtime panic.
The AI_PROVIDER Environment Variable
At runtime, AI_PROVIDER selects the active LLM client among all compiled-in providers:
export AI_PROVIDER=gemini # uses gem feature
export AI_PROVIDER=openai # uses oai feature
export AI_PROVIDER=anthropic # uses cld feature
export AI_PROVIDER=xai # uses xai feature
export AI_PROVIDER=cohere # uses co feature
export AI_PROVIDER=huggingface # uses hf feature
If AI_PROVIDER is not set, AutoGPT defaults to gemini.
opt-level = "z", LTO, symbol stripping).
Docker Deployment
AutoGPT ships two Docker images: kevinrsdev/autogpt for the agent binary and kevinrsdev/orchgpt for the orchestrator. A docker-compose.yml in the repository root wires them together.
Pre-built Images
| Image | Tag | Size | Purpose |
|---|---|---|---|
kevinrsdev/autogpt | 0.4.5 | ~12 MB | autogpt agent CLI |
kevinrsdev/orchgpt | 0.4.5 | ~12 MB | orchgpt orchestrator |
Both images are Alpine-based and stripped of debug symbols for minimal footprint.
Running a Single Agent Container
docker run -it \
-e GEMINI_API_KEY=<your_key> \
-e AUTOGPT_WORKSPACE=/workspace \
-v $(pwd)/workspace:/workspace \
--rm --name autogpt \
kevinrsdev/autogpt
The -v flag mounts a local directory so generated files persist after the container exits.
Running the Orchestrator Container
docker run -it \
-e GEMINI_API_KEY=<your_key> \
-p 8443:8443 \
--rm --name orchgpt \
kevinrsdev/orchgpt
Docker Compose (Recommended)
The docker-compose.yml in the repository root starts both services with shared networking:
services:
autogpt:
build:
context: .
dockerfile: Dockerfile.autogpt
environment:
- GEMINI_API_KEY=${GEMINI_API_KEY}
- ORCHESTRATOR_ADDRESS=orchgpt:8443
orchgpt:
build:
context: .
dockerfile: Dockerfile.orchgpt
environment:
- GEMINI_API_KEY=${GEMINI_API_KEY}
ports:
- "8443:8443"
Start both:
docker compose up --build
Docker Compose sets up a bridge network so autogpt can reach orchgpt by container name. The ORCHESTRATOR_ADDRESS=orchgpt:8443 env var tells the agent where to connect.
Building Custom Images
To build with different feature flags, edit the Dockerfile and rebuild:
# Step 1: build autogpt image
docker build -f Dockerfile.autogpt -t my-autogpt .
# Step 2: build orchgpt image
docker build -f Dockerfile.orchgpt -t my-orchgpt .
# Step 3: run
docker run -i \
-e GEMINI_API_KEY=<key> \
-t my-autogpt
Accessing the Container Workspace
After starting a container:
# Find running container ID
docker ps
# Attach shell
docker exec -it <container_id> /bin/sh
# Explore workspace
ls workspace/
# architect/ backend/ designer/ frontend/
Stop all running containers:
docker stop $(docker ps -q)
Contributing
Contributions to AutoGPT are welcome! Whether you are fixing a bug, adding a new agent, improving documentation, or proposing a protocol change, the process is straightforward.
Setting Up the Development Environment
git clone https://github.com/wiseaidotdev/autogpt.git
cd autogpt/autogpt
# Build with all features to catch compilation errors across all agents
cargo build --all-features
Running the Test Suite
cargo test --all-features
Code Style
AutoGPT targets Rust 1.89+ and enforces clippy warnings as errors in CI:
cargo clippy --all-features -- -D warnings
cargo fmt --check
Format your code before opening a PR:
cargo fmt
Commit Message Format
AutoGPT uses conventional commit prefixes:
| Prefix | Use for |
|---|---|
feat: | New features or agents |
fix: | Bug fixes |
docs: | Documentation changes |
refactor: | Code improvements without behavior change |
test: | Test additions or fixes |
chore: | Build system, CI, dependency updates |
Example: feat: add CoderGPT agent for code review tasks
Adding a New Built-in Agent
- Create
autogpt/src/agents/<your_agent>.rsimplementingExecutor - Register it in
autogpt/src/agents.rsby adding apub moddeclaration - Add a feature flag in
Cargo.tomlif the agent has optional dependencies - Re-export from
autogpt/src/prelude.rsunder the appropriatecfgblock - Write documentation in
docs/src/agents/<your-agent>.md - Add an entry to
docs/src/agents/overview.mdanddocs/src/SUMMARY.md
Adding Documentation
The docs site is built with mdBook. To preview locally:
cargo install mdbook
cd docs
mdbook serve --port 3001
# Open http://localhost:3001
Build for production:
mdbook build
# Output at docs/book/
Opening a Pull Request
- Fork the repository on GitHub
- Create a feature branch:
git checkout -b feat/my-new-feature - Make your changes and add tests where applicable
- Ensure
cargo test --all-features,cargo clippy, andcargo fmt --checkall pass - Push and open a pull request against
main
Reporting Issues
Open a GitHub Issue with:
- A clear description of the bug or feature request
- Steps to reproduce (for bugs)
- Your OS, Rust version (
rustc --version), and AutoGPT version
License
By submitting a contribution you agree that your code will be distributed under the MIT License.