Skip to main content
Xenors Xenors
XENORS
AI · Step-by-step tutorial

How to Build an AI Agent with ChatGPT: Free Options, Setup and Python Example

A practical, beginner-friendly guide to building your first AI agent: what an agent really is, what you can do for free, how to set one up inside ChatGPT, how to make one in Python, and how to keep it safe.

By Ashok Kumar Yadav · Published and updated · About 15 minutes to read

AI agent workflow showing a goal, a model, tools and a human review step
On this page
  1. Quick answer
  2. What is an AI agent?
  3. Which route should you choose?
  4. Can you build an AI agent with ChatGPT for free?
  5. How to build your first AI agent: step by step
  6. How to set up an AI agent in ChatGPT
  7. How to make an AI agent using Python
  8. How to build an AI agent like ChatGPT
  9. AI agent vs chatbot vs workflow automation
  10. Real-world example: a research assistant
  11. Safety and security basics
  12. Costs and limits to expect
  13. Common mistakes and how to avoid them
  14. Printable checklist (save as PDF)
  15. What should you build next?
  16. Frequently asked questions
  17. Official sources

Quick answer: To build an AI agent with ChatGPT, (1) pick one narrow, measurable task, (2) write precise instructions, (3) decide which tools the agent may use, (4) test it on realistic examples, and (5) require human approval for anything risky. If you want no code, start with a detailed ChatGPT conversation, or ChatGPT agent mode on a paid plan. If you want something you can deploy, use the OpenAI Agents SDK in Python or TypeScript, or OpenAI's visual Agent Builder.

Most tutorials on this topic either stay at the level of "write a good prompt" or jump straight into complicated multi-agent frameworks. This guide sits in the middle. You will learn the concepts, try a no-code version, then build a small but real Python agent, and finish with the safety and evaluation habits that separate a toy from something you can trust.

One note before we start: AI products change quickly. Where this article mentions plans, limits or features, we point to the official OpenAI documentation so you can confirm the current state before you rely on it.

What is an AI agent?

An AI agent is software that uses a language model, a set of instructions and a set of tools to pursue a goal over several steps. A normal chatbot answers a message and stops. An agent can look at the situation, decide what to do next, call a tool (such as a search, a calculator, a database or an API), read the result, and then decide whether to continue or finish.

OpenAI's own Agents SDK describes agents in simple terms: an agent is a model equipped with instructions and tools, and larger systems are built by letting agents hand work to other agents and by adding guardrails that validate inputs and outputs.

The four parts of every agent

  • Goal and instructions: what the agent is for, what it must never do, and what a good answer looks like.
  • Model: the reasoning engine that reads the situation and chooses the next step.
  • Tools: the actions the agent is allowed to take, such as searching approved sources, reading a file or creating a draft.
  • Memory and state: what the agent remembers within a task, and sometimes across tasks.

The agent loop

Behind the scenes, nearly every agent runs the same loop: observe the task and any previous results, decide the next action, act by calling a tool or writing an answer, then check the result. The loop repeats until the goal is met, a limit is reached, or a human needs to step in. Understanding this loop makes every framework easier to learn, because they are all variations of it.

AI agent architecture showing the user, the model, the tools and the results flowing back to the model
A simple agent architecture: the user gives a goal, the model chooses tools, results return to the model, and a human reviews important actions.

Which route should you choose?

"Build an AI agent with ChatGPT" can mean several different things. People use the phrase for everything from a clever prompt to a deployed application. Choosing the right route first saves a lot of time.

RouteCoding neededBest forMain limitation
Prompt-based agent in a ChatGPT chatNoDesigning and testing your agent's logic, learning, personal workflowsNot autonomous; you stay in the loop
ChatGPT agent modeNoMulti-step tasks using a browser, files and connected appsPaid plans only, with monthly usage limits
Custom GPTs / plug-insNoReusable assistants inside ChatGPTCreation options are changing; check your account
Agent Builder (visual)Little or noneDrag-and-drop workflows with guardrails and evaluationAPI-based; usage is billed at API rates
OpenAI Agents SDKYes (Python or TypeScript)Custom, deployable agents with your own toolsYou manage hosting, security and monitoring

If you are brand new, a good path is: prototype in a normal chat, then try agent mode or Agent Builder if you want to see actions happen, then move to the SDK when you need full control.

Can you build an AI agent with ChatGPT for free?

Partly, yes. Here is an honest breakdown of what "free" really covers.

What you can do for free

  • Design and test the agent's logic. In a free ChatGPT conversation you can write the role, rules, steps and output format, and test them on real examples. This is the most valuable step, and it costs nothing.
  • Use search, file uploads and data analysis within the limits of your plan. These let you simulate parts of an agent workflow manually.
  • Use existing GPTs that others have shared, subject to the limits of the Free plan.
  • Install and read the open-source SDK. The openai-agents package itself is free to install and study.

What is not free

  • ChatGPT agent mode. OpenAI's Help Center lists it for Plus, Pro, Business, Enterprise and Edu plans, not the Free plan, with monthly message limits that depend on the plan.
  • Running an agent through the API. Programmatic agents call the OpenAI API, which is billed by usage. A small learning project is usually cheap, but it is not zero.
  • Creating custom GPTs. Creating GPTs has been limited to paid or workspace accounts, and OpenAI has signalled a move toward plug-ins. Do not build your plan around outdated GPT Builder tutorials; check what your own account offers.

Be careful with "free AI agent" claims. Any page that promises a fully autonomous, free, unlimited agent is overselling. Free tools are excellent for learning and prototyping. Reliable automation that acts on your behalf nearly always involves paid compute somewhere.

How to build your first AI agent with ChatGPT: step by step

These eight steps work whichever route you choose. Do them in order. Most failed agents skip steps 1, 2 and 7.

  1. Choose one narrow, measurable task. "Turn raw meeting notes into a clean action list with owners and deadlines" is a good first agent. "Run my business" is not. A narrow task is easier to test, cheaper to run and safer to trust.
  2. Define success before you build. Write down what a correct result looks like. For the meeting-notes agent: every action has an owner, no action is invented, and dates are copied exactly. You will use this definition to judge the agent later.
  3. Write the instructions. State the agent's role, the steps it should follow, what it must never do, and the exact output format. Be specific. Vague instructions create vague agents.
  4. List the inputs and outputs. What does the agent receive (text, a file, a URL)? What must it return (a table, JSON, a short email draft)? Fixed formats make results easier to check automatically.
  5. Choose the minimum set of tools. Start with none. Add a tool only when the task cannot be done without it. Every tool is a new way for things to go wrong.
  6. Add approval points. Anything that sends, publishes, pays, deletes or changes data should pause for a human yes or no. Drafting is safe; sending is not.
  7. Test with realistic examples. Collect at least 10 to 20 real inputs, including messy and tricky ones. Run the agent on all of them and compare results with your success definition from step 2.
  8. Improve, then automate. Fix the most common failures by tightening instructions or adding a tool. Only after the manual workflow is reliable should you consider scheduling it or deploying it.

How to set up an AI agent in ChatGPT

This is the no-code route. It is perfect for learning how an agent should behave before you write any code.

Option A: A prompt-based agent in a normal chat

Open a new ChatGPT conversation and paste a structured prompt like the one below. Replace the bracketed parts with your own details.

ROLE
You are a meeting-notes agent for a small product team.

GOAL
Turn the raw notes I paste into a clear action list.

RULES
- Use only information that appears in the notes. Never invent owners or dates.
- If an owner or deadline is missing, write "Unassigned" or "No date".
- Do not send, publish or share anything. Draft only.

STEPS
1. Read the notes and list every decision and every action.
2. For each action, identify owner, deadline and priority.
3. Flag anything ambiguous and ask me one question about it.

OUTPUT FORMAT
A table with columns: Action | Owner | Deadline | Priority | Source line.
Then a short "Questions for you" list.

APPROVAL
Before you produce a final version, show me the draft and wait for my OK.

Now paste in some real notes and watch how it behaves. Where it makes mistakes, edit the rules. Each fix teaches you something about instruction design that carries over to any agent you build later.

Option B: ChatGPT agent mode (paid plans)

On eligible paid plans, ChatGPT offers an agent mode that can reason through a task and use tools such as a browser, files and connected apps. You can open it from the Tools menu or by typing /agent in the message box, according to OpenAI's help documentation. It can pause to ask permission before consequential actions, and you can interrupt it or take over the browser.

Tips for good results in agent mode:

  • Give a specific outcome, for example "Compare these three tools on price, features and support, and give me a table with source links," rather than "research tools."
  • State what it should not do, such as "Do not log in to anything" or "Do not make purchases."
  • Do not share passwords or highly sensitive data. Review what it did before you act on the result.
  • Check your plan's monthly agent limits in the official help article before you plan heavy use.

Option C: Reusable assistants inside ChatGPT

Custom GPTs let people save instructions and knowledge files as a reusable assistant. However, creation options have been changing, and OpenAI has said it plans to steer workflows toward plug-ins. If you see an old tutorial that tells you to click "Create a GPT," confirm that the option exists in your account first. If it does not, keep your tested prompt from Option A in a Project or a notes file, and move to the SDK when you need a persistent, deployable agent.

Option D: Agent Builder (visual, API-based)

OpenAI's AgentKit includes Agent Builder, a visual canvas for designing multi-step agent workflows with nodes, logic, guardrails and evaluation tools. It launched in beta, so features and availability may change. It is a good bridge between no-code experimentation and full code, and its usage is billed through the standard API pricing rather than a separate subscription.

How to make an AI agent using Python

This is the route that gives you a real, deployable agent. You will use the OpenAI Agents SDK, a lightweight library whose core ideas are agents, tools, handoffs and guardrails. The examples below follow the official quickstart pattern.

Step 1: Set up your environment

You need Python installed. Create a project folder and a virtual environment so your packages stay tidy.

mkdir my_first_agent
cd my_first_agent
python -m venv .venv

# macOS / Linux
source .venv/bin/activate
# Windows (PowerShell)
# .venv\Scripts\Activate.ps1

pip install openai-agents

# Set your key as an environment variable (never paste it into code)
export OPENAI_API_KEY="your-key-here"

Protect your API key. Never put it in browser JavaScript, a public repository or a screenshot. Run agents on your own computer or on a server you control. If a key leaks, revoke it immediately in your OpenAI dashboard.

Step 2: Create and run a minimal agent

# agent_basic.py
from agents import Agent, Runner

agent = Agent(
    name="Study Planner",
    instructions=(
        "Create a practical study plan. "
        "Ask for missing details. "
        "Do not claim to perform external actions."
    ),
)

result = Runner.run_sync(agent, "Create a 7-day Python beginner study plan")
print(result.final_output)

Run it with python agent_basic.py. This agent has no tools, so it can only think and write. That is intentional. It proves your setup works and shows you how instructions shape behaviour.

Step 3: Give the agent a tool

A function tool is just a Python function the agent is allowed to call. Add a clear docstring, because the model uses it to decide when the tool is useful.

# agent_tool.py
from agents import Agent, Runner, function_tool

@function_tool
def days_until(target_date: str) -> str:
    """Return how many days remain until a date in YYYY-MM-DD format."""
    from datetime import date
    y, m, d = map(int, target_date.split("-"))
    delta = (date(y, m, d) - date.today()).days
    return f"{delta} days"

agent = Agent(
    name="Deadline Helper",
    instructions=(
        "Help the user plan around deadlines. "
        "Use the days_until tool for date maths instead of guessing."
    ),
    tools=[days_until],
)

result = Runner.run_sync(agent, "My exam is on 2026-12-15. How long do I have?")
print(result.final_output)

Notice the design choice: the tool does exactly one safe, read-only thing. Start with tools like this. Tools that write, send or delete should come later and should require approval.

Step 4: Split work between specialist agents

When one agent handles too many jobs, quality drops. The SDK supports handoffs, where a router agent passes the request to a specialist.

# agent_handoff.py
from agents import Agent, Runner

python_tutor = Agent(
    name="Python Tutor",
    instructions="Explain Python concepts simply with a short example.",
)

career_coach = Agent(
    name="Career Coach",
    instructions="Give practical, honest advice on learning paths and job skills.",
)

router = Agent(
    name="Router",
    instructions="Decide whether the question is about coding or careers, then hand off.",
    handoffs=[python_tutor, career_coach],
)

result = Runner.run_sync(router, "What is a list comprehension?")
print(result.final_output)

Only move to multiple agents after a single agent works well. Extra agents add cost, delay and new ways to fail.

Step 5: Look at the traces

The SDK includes tracing for the normal server-side path. After your first successful run, open the Traces dashboard in the OpenAI platform to see each model call, tool call and handoff. Reading traces is the fastest way to understand why an agent made a strange decision, and it should be your first debugging step before you rewrite any prompts.

Tip: Package names, function signatures and features can change between SDK versions. If a snippet fails, check the official quickstart linked in the sources section for the current syntax.

How to build an AI agent like ChatGPT

Many people searching this phrase actually want to build a chat product of their own, with a web interface, conversation history and the ability to use tools. That needs more than a prompt. A typical architecture has these layers:

  • Front end: a chat interface that sends the user's message to your server and streams the reply back.
  • Back end: your server holds the API key, applies authentication and rate limits, and calls the model. Never call the model directly from browser code.
  • Agent layer: the instructions, tools and handoffs described above.
  • State and memory: conversation history stored per user, either by passing earlier messages back in, using SDK sessions, or using server-managed conversation state.
  • Retrieval: optional search over your own documents so answers are grounded in your content.
  • Safety layer: input and output checks, moderation, logging and spending limits.
  • Observability: traces, error tracking and a feedback button so you learn from real use.

Build it in this order: one agent, one simple chat page, then history, then retrieval, then more tools. Resist the urge to add multi-agent orchestration on day one. If you want a ready-made chat front end, OpenAI's ChatKit is designed for embedding agent chat experiences, though you should confirm its current status in the docs.

AI agent vs chatbot vs workflow automation

Not every problem needs an agent. Choosing the simplest tool that works will save you money and headaches.

TypeHow it worksBest whenWatch out for
ChatbotReplies to messages, no actionsQ&A, drafting, explainingCannot complete multi-step jobs by itself
Workflow automationFixed steps triggered by eventsPredictable, repetitive processesBreaks when input varies a lot
AI agentChooses among tools and adapts to resultsVariable tasks where the path is not known in advanceMore cost, more testing, less predictability

A useful rule of thumb: if you can draw the whole process as a fixed flowchart, use a normal workflow, maybe with a model call in one step. If the right next step depends on what the previous step found, an agent is worth considering.

Real-world example: a research assistant

Let us design a research assistant from start to finish, using the steps from earlier.

The spec

  • Task: take a question, search approved sources, and produce a short summary with links.
  • Tools: web search (read-only) and a note-taking function that stores URLs and key facts.
  • Rules: every factual claim needs a source link; if sources disagree, say so; if evidence is weak, say that instead of guessing.
  • Approval: the agent drafts a summary, and a human reviews it before it is emailed or published.

How you would test it

Prepare at least 20 test questions across easy, medium and tricky topics. For each answer, check three things: Are the cited sources real and relevant? Does each claim match its source? Did the agent admit uncertainty when evidence was thin? Record a simple score for each, plus completion time and cost. This small evaluation set will tell you more than any amount of impressions.

What usually goes wrong

  • It cites a source that does not actually support the claim. Fix: require a short supporting quote or a section reference for each claim, and spot-check.
  • It trusts instructions hidden inside a web page. Fix: treat retrieved content as data, never as commands (see the safety section).
  • It loops on searches. Fix: set a maximum number of steps and a time limit.

Safety and security basics

An agent that can act is more useful and more risky than a chatbot that only talks. These habits matter from your very first prototype.

  • Least privilege. Give the agent only the tools and data access the task requires. A research agent does not need to send email.
  • Human approval for consequential actions. Sending messages, spending money, deleting files and publishing content should always need a person's confirmation.
  • Defend against prompt injection. Web pages, emails and documents can contain hidden text that tries to give the agent new instructions. Tell the agent in its instructions that retrieved content is untrusted information, not commands, and keep high-risk tools away from agents that read untrusted content.
  • Use guardrails. Validate inputs and outputs, for example blocking personal data from leaving your system or rejecting malformed results.
  • Protect secrets. Keep API keys in environment variables or a secrets manager, rotate them, and never expose them to the browser.
  • Log and monitor. Keep traces and logs so you can see what the agent did and why.
  • Set budgets and stop switches. Cap steps, time and spending per task, and give yourself a simple way to halt the agent.
  • Respect privacy and policy. Do not feed an agent other people's sensitive data without a lawful reason, and follow OpenAI's usage policies and the laws that apply to you.

Costs and limits to expect

Costs depend on the route you choose, so here is how to think about each one rather than quoting numbers that may change.

  • Prompt-based agent in ChatGPT: covered by your normal plan and its usage limits.
  • Agent mode: requires an eligible paid plan and has monthly message limits that vary by plan. Check OpenAI's help article for the current figures.
  • Agent Builder and the Agents SDK: billed by API usage, mainly the amount of text the model reads and writes plus any hosted tools you use. Longer instructions, more tool calls and more handoffs mean more cost.
  • Hosting: if you deploy your own application, add the cost of your server or cloud service.

To keep spending predictable, set a monthly budget in your API dashboard, keep instructions concise, limit the number of steps per run, and test with small inputs first. Always confirm current pricing on OpenAI's official pricing pages.

Common mistakes and how to avoid them

MistakeWhy it hurtsFix
A goal that is too broadThe agent wanders and results are unpredictablePick one narrow task with a clear success test
Too many tools at onceMore ways to fail and more security riskStart with zero tools and add one at a time
No evaluation setYou cannot tell whether changes helpKeep 20+ realistic test cases and rerun after every change
Hardcoded secretsLeaked keys lead to abuse and billsUse environment variables and rotate keys
No logging or tracesFailures are impossible to diagnoseUse tracing and keep logs
No step or time limitsRunaway loops and surprise costsSet maximum steps, timeouts and budgets
Trusting retrieved contentPrompt injection can hijack the agentTreat external text as data; restrict risky tools
Skipping human reviewMistakes reach real peopleRequire approval before any external action
Following outdated tutorialsFeatures and menus change quicklyVerify against the official docs before you start

Printable checklist (save as PDF)

Use this checklist before you trust any agent with real work. Click the button, then choose "Save as PDF" in your browser's print dialog to keep a copy.

  • The task is narrow and I wrote down what success looks like.
  • Instructions cover role, steps, rules and output format.
  • The agent has only the tools it truly needs.
  • Risky actions need my approval.
  • Retrieved content is treated as untrusted data.
  • API keys are stored securely and never exposed in the browser.
  • I tested at least 20 realistic examples and recorded the results.
  • Step, time and budget limits are set, and I can stop the agent.
  • Traces or logs are on so I can review what happened.
  • I checked the official docs for current features, plans and pricing.

What should you build next?

After your first working prototype, improve it in this order:

  1. Add retrieval over trusted documents so answers are grounded in your own material.
  2. Use structured outputs so results are easy to validate and pass to other systems.
  3. Build an evaluation routine that scores success rate, quality, speed and cost every time you change something.
  4. Add guardrails for inputs and outputs.
  5. Then consider multiple agents, only if one agent is clearly overloaded.

Keep learning with more tutorials in Xenors AI and Tech, and recheck the official documentation regularly, because ChatGPT features and developer APIs change often.

Frequently asked questions about building AI agents

How do I build an AI agent with ChatGPT?

Choose one narrow task, write clear instructions, decide which tools the agent may use, test on realistic examples and add human approval for risky actions. Use a ChatGPT conversation or agent mode for no-code experiments, and the OpenAI Agents SDK or Agent Builder for something you can deploy.

Can I build an AI agent with ChatGPT for free?

You can design and test the agent's logic in a free chat. ChatGPT agent mode is not on the Free plan, and API-based agents are billed by usage, so a deployed agent usually has a small cost.

How do I set up an AI agent in ChatGPT?

Write a structured prompt with role, goal, rules, steps, output format and approval points. On eligible paid plans you can also open Agent mode from the Tools menu or type /agent. Review its actions before it sends or publishes anything.

How do I make an AI agent using Python?

Install openai-agents, set OPENAI_API_KEY securely, create an Agent with instructions and run it with Runner.run_sync. Add function tools only when the task requires them.

How do I build an AI agent like ChatGPT?

You need a chat interface, a secure back end that holds your key, a model, conversation state, optional retrieval, tool execution, rate limits, logging and moderation. Start with a single agent and a simple page.

Is an AI agent the same as ChatGPT?

No. ChatGPT is a conversational product. An agent is a system that uses a model, instructions and tools to work toward a goal across several steps.

Can I make an AI agent without coding?

To a degree. You can use detailed prompts, agent mode on paid plans or the visual Agent Builder. For reliable production use, you still need testing, monitoring and security review.

How long does it take to build a first AI agent?

A simple prototype can take an afternoon. A dependable production agent usually takes weeks because of evaluation, monitoring and security work.

Do I need an API key?

Not to experiment in the ChatGPT app. You need an API key to build a programmatic agent with the Agents SDK.

How do I stop an AI agent from making mistakes?

Narrow its goal, limit its tools, validate inputs and outputs, require approval for consequential actions and test it on a fixed set of examples. You cannot remove mistakes completely, so design for review.

Official sources and further reading

Verify plans, limits and API details against these resources before you build:

Disclaimer: This is an educational tutorial. Product features, plans and prices are set by OpenAI and may change. Always confirm current details in the official documentation.

Continue exploring