Build Your First Agent
This content was developed with AI assistance and is regularly reviewed for accuracy.
Snapshot: October 2026. Model names, prices, and product features change monthly; What's New in AI is the maintained chronology.
You are going to build a working agent in the next hour: one that researches a topic on a schedule and delivers a report you can trust enough to skim. There are two paths. The no-code path uses the agent mode inside Claude or ChatGPT and takes about forty-five minutes. The code path uses Python and the Claude API, takes about ninety, and ends with a multi-model pipeline you can adapt to real work. Both paths teach the same five parts every agent has: a brief, tools, a loop, a stop condition, and a check.
Last tested with Claude Opus 5.5 and the Claude app's scheduled tasks in October 2026.
Learning focus
- Write a brief an agent can act on without you in the room
- Give an agent tools and context with the minimum reach the job needs
- Run attended first, then schedule, then verify
- (Code path) Implement the agent loop against the API with current model ids and handle every stop reason
Prerequisites
For the no-code path you need a Claude account (the free tier allows up to five Projects; scheduled tasks start at Pro) or a paid ChatGPT plan other than Free or Go for ChatGPT Work and scheduled tasks. For the code path you need Python 3.10 or later, an Anthropic API key, and pip install anthropic. Either way, bring one task you do weekly that touches files or the web but not money.
The five parts of every agent
Before either path, name the parts. The brief states the outcome and the boundaries. Tools are what the agent may call: web search, a folder, a connector, a script. The loop is the agent deciding, acting, observing, and deciding again. The stop condition is how it knows it is done, or when to give up. The check is how you verify the result. Beginners skip the last two, and that is where agents wander and where "it looked fine" turns into a wrong report sent to a client.
Path A: no code
Step 1: write the brief
Replace the old habit of "write a system prompt that gives it a persona" with a six-field brief. Here is one for a weekly competitive-intelligence report.
Objective: Produce a weekly competitive intelligence report on [competitor 1],
[competitor 2], and [competitor 3] covering product launches, pricing changes,
and notable press from the past 7 days.
Context: The reader is [our product team]. They want to know what changed and
what we should do about it, not a history of each company.
Resources: Web search. The folder [Competitive/Reports] for past reports so you
can compare. Nothing else.
Constraints: Cite a source for every claim. Mark anything you could not confirm
on the company's own site as UNVERIFIED. Omit any competitor with no notable
activity this week. Do not send or share anything; save only.
Output: A markdown report under 1,200 words with an executive summary, one
section per competitor, a "what changed since last week" section, and 2-3
recommended actions. Save it to [Competitive/Reports] as [YYYY-MM-DD-report.md].
Verification: I will spot-check three cited claims against their sources and
compare the "what changed" section to last week's report.
Every field earns its place. Resources and Constraints are the safety controls; Output and Verification are what make the result checkable.
Step 2: give it a home
In Claude, create a Project, paste the brief into the project instructions, and attach last week's report (or a sample) as a file. In ChatGPT, create a Project with the same instructions and plan to run it through ChatGPT Work. In Gemini, a Gem holds the instructions. Note that since August 2026 individual ChatGPT accounts can no longer create Custom GPTs; Projects and Workspace Agents are the replacements.
Step 3: grant tools, narrowly
Turn on web search. If your report needs a folder, connect only that folder, read-only if the app offers it. Do not connect email or calendar for a research task; every connector you add widens what the agent can read and, through Routines or similar, what it can write. If you are unsure whether a connector is needed, leave it off and see whether the agent asks.
Step 4: run it attended
Send the brief and watch the steps. The first run is diagnostic. Where the agent guesses (it picks a date range you did not mean, it includes a competitor you excluded), add a line to the brief rather than correcting in chat. After two failed corrections, stop and rewrite the brief; arguing with a run teaches you nothing the next run will remember. When the output is right, check the three cited claims you promised to check.
Step 5: schedule it and keep checking
In Claude, hand the task off as a scheduled task (Pro and up) so it runs in the cloud on Monday mornings; Claude Code's cloud Routines do the same job with a minimum interval of one hour and use your connectors. In ChatGPT, use scheduled tasks, which run at most once per hour. For a pipeline across several apps (fetch, analyze, post to Slack), Zapier Agents, Make, or n8n carry the schedule and the handoffs, and Relay.app adds a human-approval step between them.
Then spot-check the first three scheduled runs as carefully as the first attended one. Anthropic's own Routines documentation puts the rule plainly: a green status in the run list does not mean the task in your prompt succeeded. It means the run finished.
Variation: email triage
The same five parts build a triage agent. The brief defines four categories (urgent, needs response, informational, low priority) with one-line definitions and two examples each; the tool is a read-only view of one mail label; the output is a classification plus a one-sentence reason and a suggested action per message; the stop condition is the end of the label; the check is you reviewing every "urgent" and every drafted reply before anything is sent. Start on one label, not the whole inbox, and move to automation only after a week of agreement with your own judgment.
Path B: code
Step 1: the manual agent loop
The loop below is the smallest honest agent: a model, a server-side web search tool, one custom tool that writes a file behind an approval prompt, and handling for every stop reason the API can return. It uses Anthropic's current default model id; Claude's current models reason by default, so there is no thinking parameter to set, and depth is controlled with the effort setting.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
TOOLS = [
{"type": "web_search_20260209", "name": "web_search", "max_uses": 8},
{
"name": "save_report",
"description": "Save the finished markdown report to disk. Call once, at the end.",
"input_schema": {
"type": "object",
"properties": {
"filename": {"type": "string"},
"content": {"type": "string"},
},
"required": ["filename", "content"],
},
},
]
def save_report(filename: str, content: str) -> str:
if "/" in filename or not filename.endswith(".md"):
return "Refused: filename must be a plain .md name"
with open(filename, "w") as f:
f.write(content)
return f"Saved {filename} ({len(content)} characters)"
def run_agent(brief: str, max_turns: int = 12) -> str:
messages = [{"role": "user", "content": brief}]
spent = {"input": 0, "output": 0}
for _ in range(max_turns):
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
output_config={"effort": "high"},
system=(
"You are a careful research agent. Cite a source for every claim. "
"Mark anything you could not verify as UNVERIFIED."
),
tools=TOOLS,
messages=messages,
)
spent["input"] += response.usage.input_tokens
spent["output"] += response.usage.output_tokens
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason == "end_turn":
print(f"Tokens used: {spent}")
return "".join(b.text for b in response.content if b.type == "text")
if response.stop_reason == "pause_turn":
continue # a long server-side search paused; re-sending the history resumes it
if response.stop_reason == "refusal":
category = response.stop_details.category if response.stop_details else "unspecified"
return f"Stopped: the model declined this task ({category})"
if response.stop_reason == "max_tokens":
return "Stopped: output limit reached; raise max_tokens or narrow the brief"
if response.stop_reason == "tool_use":
results = []
for block in response.content:
if block.type == "tool_use" and block.name == "save_report":
print(f"Agent wants to write {block.input['filename']}")
if input("Approve? (y/n): ").strip().lower() == "y":
output = save_report(**block.input)
else:
output = "User declined. Do not retry; return the report as text instead."
results.append(
{"type": "tool_result", "tool_use_id": block.id, "content": output}
)
messages.append({"role": "user", "content": results})
return "Stopped: turn budget exhausted"
if __name__ == "__main__":
brief = open("brief.txt").read() # the six-field brief from Path A
print(run_agent(brief))
Three details carry the safety lessons of the rest of this track. The max_turns cap is the stop condition; without it a confused agent loops until your budget is gone. The approval prompt in front of the only tool that changes the world is the approval gate. The filename check inside save_report is least privilege: the tool itself refuses paths it should never touch, so the agent cannot be talked into writing elsewhere. Web search runs on Anthropic's servers and needs no handler; only your own tools do. The pause_turn branch matters because server-side search can pause a long turn, and the right response is to re-send the history, not to add a "continue" message.
Step 2: run it
export ANTHROPIC_API_KEY=your_key
python research_agent.py
Read the whole report before trusting it, then check the token counts the script printed. Cost per completed task, not per request, is the number to track.
Step 3: the multi-model pipeline
Real agents rarely use one model for everything. The classic pattern is a cheap, fast model for high-volume structured steps and a strong model for synthesis. This exercise, adapted from the former AI 201 hands-on set, builds a content-analysis pipeline for a news desk.
Requirements: ingest at least ten articles (from RSS or saved URLs); for each, produce sentiment, up to three topic tags, and named entities; then produce a headline and two-sentence summary; store results as JSON ready for a database. Use Claude Haiku 5.5 for the per-article extraction and Claude Opus 5.5 for the summaries.
import json
def classify(article_text: str) -> dict:
response = client.messages.create(
model="claude-haiku-5-5",
max_tokens=1024,
system=(
"Return only a JSON object with keys: sentiment (positive, neutral, or negative), "
"topics (list of up to 3 short strings), entities (object with lists people, "
"places, organizations). No prose."
),
messages=[{"role": "user", "content": article_text}],
)
text = "".join(b.text for b in response.content if b.type == "text")
return json.loads(text)
def summarize(article_text: str, tags: dict) -> str:
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=2048,
messages=[{
"role": "user",
"content": (
"Write a headline and a two-sentence summary for this article. "
f"Tags already assigned: {json.dumps(tags)}\n\n{article_text}"
),
}],
)
return "".join(b.text for b in response.content if b.type == "text")
Wrap json.loads in a try/except that retries once with the error appended, and log every failure; for production, the API's structured-outputs option guarantees the schema, and Development and APIs shows the current syntax. Success criteria for the exercise: the pipeline processes ten test articles; the JSON is consistent and valid for all ten; failed calls and malformed articles are handled without crashing the run; you can state the cost per article and name the step you would move to a cheaper model or cache; and someone else can reproduce it from your notes.
Where the code path goes next
The manual loop is the right first build because it hides nothing. Once you understand it, the Anthropic SDK's tool runner removes the loop code for tools you define, the Claude Agent SDK gives you the Claude Code harness with built-in file and shell tools, and Managed Agents runs the loop and a sandbox on Anthropic's side. For developers who want a zero-code agent today, claude -p "your brief" in Claude Code is a complete agent with files, shell, and web already wired; the Claude Code guide covers it.
Common mistakes
Asking one agent to do everything at once produces mediocre results across all of it; start with one job. Thin briefs make the agent guess; the six fields exist because each guess is a future error. Skipping the attended run means the first time you see a mistake is in a scheduled report. Trusting green status is the quiet one; verify the output, not the run. And choosing a platform above your skill level leads to frustration; the no-code path is a real agent, not a warm-up.
Measuring whether it helped
After two weeks, estimate time saved per week against the time you now spend reviewing. Spot-check five to ten outputs a week; if more than 20 percent need significant edits, the brief needs work. Keep a one-line log of every error and its fix. And ask the people who receive the output whether it is useful; an agent that saves you an hour and costs your team two is not a win.
Key takeaways
- Every agent has five parts: brief, tools, loop, stop condition, check. The last two are the ones beginners skip.
- The six-field brief (objective, context, resources, constraints, output, verification) replaces persona prompts and carries the safety controls.
- Run attended, then schedule, then keep spot-checking; a finished run is not a correct run.
- In code, cap turns, gate the tools that change the world, and handle every stop reason including
pause_turnandrefusal. - Use a cheap model for high-volume structured steps and a strong one for synthesis, and measure cost per completed task.
Next steps
- Continue to: Patterns and Multi-Agent Systems
- Turn your brief into something reusable: Skills, AGENTS.md, and CLAUDE.md
- Before you connect anything that can write: Agent Safety and Guardrails
- A full cross-app pipeline with a classifier: Tutorial: Build an Inquiry Router With an AI Classifier