Build Your First AI Agent
In this tutorial you will install OpenClaw, configure your API key, create a simple research agent from scratch, and run your first task end-to-end. Estimated time: 15 minutes.
Prerequisites
- Python 3.10+ installed (
python --version) - An OpenAI API key (or a free Ollama install for local models)
- A terminal / command prompt
Step 1 — Install OpenClaw
pip install openclaw
# Verify the install
openclaw --version
# OpenClaw 1.5.2Step 2 — Configure Your API Key
openclaw config initThe init wizard will prompt you to choose a provider and paste your API key. It creates ~/.openclaw/config.yaml:
# ~/.openclaw/config.yaml (auto-generated)
llm:
provider: openai
model: gpt-4o-mini
api_key: "${OPENAI_API_KEY}"
memory:
type: local
path: ~/.openclaw/memory/# Set the environment variable (Linux/Mac)
export OPENAI_API_KEY="sk-..."
# Windows PowerShell
$env:OPENAI_API_KEY = "sk-..."Step 3 — Run Your First Task (No Config File Needed)
openclaw run "What are the 3 most important things to know about Python type hints?"OpenClaw uses the default agent profile from config.yaml and starts reasoning. You'll see the thinking steps in real time:
📎 Task: What are the 3 most important things to know about Python type hints?
💡 Thinking: I'll answer this from my training knowledge
📄 Generating response...
**1. Type hints are not enforced at runtime**
Python type hints (PEP 484) are annotations only — Python does NOT
raise an error if you pass the wrong type. Use mypy or pyright to
enforce them statically...
**2. Use `Optional[X]` for values that can be None**
...
**3. `TypeVar` enables generic functions**
...
✅ Done | 0.03s | 312 tokens | $0.0001Step 4 — Create Your First Agent File
Now let's create a reusable agent with custom tools. Create a file called my-agent.yaml:
# my-agent.yaml
name: research-helper
description: "Searches the web and summarizes findings"
llm:
model: gpt-4o-mini
temperature: 0.3
system_prompt: |
You are a concise research assistant. When given a topic:
1. Search for recent information
2. Read the top 3 sources
3. Summarize the key findings in bullet points
4. Include source URLs
tools:
- web_search
- read_url
memory:
type: episodic # Remember what we've discussed this session
output:
format: markdown # Return Markdown-formatted textopenclaw run --config my-agent.yaml "Research the latest developments in Rust programming language"Step 5 — Understand the Output
OpenClaw logs each step so you can see exactly what the agent did:
# See detailed trace of the last run
openclaw logs --last 1 --verbose
# Save output to a file
openclaw run --config my-agent.yaml "Research quantum computing" --output report.mdNext Steps
- Try the Web Scraper Agent tutorial to extract structured data
- Add a custom tool — see the Tool Creation guide
- Schedule this agent to run daily — see Event-Driven
Step 1 — Install and Verify OpenClaw
Before creating your first agent, confirm that OpenClaw is correctly installed. Open a terminal and run openclaw --version. You should see output like openclaw 1.x.x. If you see a "command not found" error, follow the installation guide for your platform before continuing.
Next, verify your API key is configured. Run openclaw config show and confirm the llm.api_key field contains your key (it will be partially masked). If it shows not set, run openclaw config set llm.api_key YOUR_KEY to configure it. OpenClaw defaults to using Claude via the Anthropic API, so you'll need a valid Anthropic API key for this tutorial.
Step 2 — Create Your Agent Configuration
Create a new directory for this project and navigate into it:
mkdir my-first-agent
cd my-first-agent
Create a file called agent.yaml with the following content:
agent:
name: my-first-agent
description: A simple agent that answers questions
system_prompt: |
You are a helpful assistant. Answer the user's questions
clearly and concisely. If you don't know the answer,
say so rather than guessing.
llm:
model: claude-3-5-sonnet-20241022
temperature: 0.7
max_tokens: 1024
This is the simplest valid agent configuration. The system_prompt defines the agent's personality and role. The llm section specifies which model to use and how to call it.
Step 3 — Run Your First Task
Run the agent with a simple task:
openclaw run --config agent.yaml --task "What is the capital of France?"
You should see output similar to:
Agent: my-first-agent
Task: What is the capital of France?
─────────────────────────────────────
The capital of France is Paris. It has been the capital since...
─────────────────────────────────────
Run completed in 1.2s
Congratulations — you've just run your first OpenClaw agent. The agent received your task, sent it to the LLM with the system prompt prepended, and returned the response.
Step 4 — Add a Tool
Agents become far more useful when they can interact with the world through tools. Let's add a web search tool so the agent can look up current information. Update your agent.yaml:
agent:
name: my-first-agent
description: A helpful assistant with web search
system_prompt: |
You are a helpful assistant with access to web search.
When answering questions about current events, recent data,
or factual claims you are unsure about, use the web_search
tool to look up accurate information before responding.
llm:
model: claude-3-5-sonnet-20241022
temperature: 0.7
max_tokens: 2048
tools:
- name: web_search
enabled: true
Now run a question that requires current information:
openclaw run --config agent.yaml --task "What was announced at the latest OpenAI event?"
Watch the output — you'll see the agent invoking the web_search tool, receiving results, and then synthesizing a response. The agent's reasoning is visible in verbose mode (--verbose), where you can see each tool call and its result.
Step 5 — Run in Interactive Mode
For multi-turn conversations, use interactive mode:
openclaw start --config agent.yaml
This starts a persistent agent session. You can send multiple messages and the agent maintains context across the conversation. Press Ctrl+C to exit. Interactive mode is useful for exploratory sessions where you don't know in advance exactly what you want to ask.
Troubleshooting
If you see an AUTHENTICATION_FAILED error, your API key is invalid or not configured. Run openclaw config set llm.api_key YOUR_ACTUAL_KEY with a valid key. If you see LLM_RATE_LIMITED, you've hit your provider's rate limit — wait 30 seconds and try again. If the agent produces no output, check your system prompt — a confused system prompt can cause the model to produce empty responses.
Next Steps
Now that you have a working agent, explore more capabilities. Add file system tools with tools: [{name: file_read}] to let the agent read files. Set a persistent memory directory with agent.memory_dir: ./memory to give the agent state across runs. Chain multiple tools together for more complex tasks. The tutorials in this section cover specialized agents built on these same foundations — work through them to see what's possible.
Agent Design Best Practices
The quality of your system prompt is the single biggest factor in agent performance. A well-crafted system prompt sets clear behavioral boundaries, defines the agent's persona, specifies the output format you expect, and anticipates edge cases. A vague system prompt produces vague behavior — the model fills in unspecified gaps with its general training behavior, which may not match your intentions.
Test your agent against a range of inputs before deploying it. Include edge cases: empty inputs, very long inputs, inputs in unexpected languages, inputs that ask the agent to do things outside its intended scope. Does the agent handle "I want you to ignore your previous instructions" appropriately? Does it stay on-task when given a confusing or contradictory input? Systematic testing reveals prompt gaps that aren't visible from testing happy paths alone.
Set a budget for agent runs, especially during development. Use the --max-steps flag when running agents that use tools — this prevents runaway loops where the agent calls tools in an endless cycle. Start with a low limit (10 steps) during development and increase it once you understand how many steps your typical task actually needs. The step count in the run output tells you exactly how many steps each task used, giving you data to set an appropriate limit.
Version your agent configurations the same way you version code. Store agent.yaml files in Git, use branches for experiments, and tag releases. When an agent's behavior changes unexpectedly, being able to diff agent.yaml versions often immediately reveals the cause — a prompt change, a model version update, or a tool config modification. Treat agent configs as code, not as throw-away configuration.
Understanding Token Usage and Costs
Each LLM call consumes tokens — your system prompt, the conversation history, tool results, and the response all count toward the token usage for that call. For agents that use tools, each tool call adds the tool result to the context, which accumulates quickly. A long-running agent might accumulate thousands of tokens of tool results across its steps, significantly increasing the cost of each subsequent LLM call. Use openclaw run --show-costs to see token usage and estimated cost per run during development, helping you optimize expensive agent workflows before they run at scale.