پرش به محتوا

محتوای اصلی این صفحه به زبان انگلیسی است.ترجمهٔ این صفحه

هوش مصنوعی عامل‌محور

How to Build an AI Agent from Scratch (Step-by-Step Guide)

Build an AI agent that plans, uses tools and completes tasks: the agent loop, tool design, memory, guardrails, evaluation and when to use multiple agents.

تحریریهٔ IQrows · به‌روزرسانی · 3 دقیقه مطالعه

اشتراک‌گذاری
A blue industrial robot arm next to a humanoid robot at a technology fair
Photo: Humanrobo, CC BY-SA 3.0, via Wikimedia Commons

A chatbot answers. An AI agent gets things done: it plans, uses tools, checks results and keeps going until the goal is met. Here is how to build one from scratch, then make it reliable and safe. (New to the idea? Read what is agentic AI?)

Agent, workflow or chatbot?

  • Chatbot: one question, one answer.
  • Workflow: fixed steps you designed (always: fetch → summarise → email).
  • Agent: the model decides the next step based on what it finds.

Use an agent only when the steps depend on what happens along the way. If the steps never change, a workflow is cheaper and more reliable.

Step 1: Define the goal and the ابزار

Write the task as a checklist a new employee could follow. That reveals the tools you need. For a research agent, for example: web_search(query), read_page(url) and save_note(text).

Good tools:

  • do one clear thing,
  • have a descriptive name and a description with an example,
  • take simple, validated inputs,
  • return short, structured results (long outputs confuse models and cost tokens).

Step 2: Write the agent loop

Most model APIs support tool calling: you describe your tools, the model replies with a request to call one, your code runs it and sends back the result. Wrap that in a loop:

# The agent loop (pseudo-code; adapt to your provider's tool-calling API)
messages = [system("You are a research agent. Plan, use tools, cite sources."), user(task)]

for step in range(8):                        # hard step limit
    reply = llm(messages, tools=TOOLS)
    messages.append(reply)
    if not reply.tool_calls:                 # no more tools: final answer
        print(reply.text)
        break
    for call in reply.tool_calls:
        result = run_tool(call.name, call.arguments)   # validate inputs first!
        messages.append(tool_result(call.id, result))
else:
    print("Stopped: step limit reached")

That is the whole idea: think → act → observe → repeat. Building it yourself once makes every agent framework easy to understand.

Step 3: Add planning

For longer tasks, ask the agent to write a short plan (a to-do list) first and update it as it works. Explicit plans make agents more reliable and much easier to debug.

Step 4: Add memory

  • Short-term memory is the conversation and tool results in the context window.
  • When it gets long, summarise older steps.
  • Long-term memory stores useful facts in a database for future sessions.

Save the agent’s state so a task can resume after an error or a human approval.

Step 5: Connect real tools with MCP and RAG

Instead of writing every integration yourself, connect MCP servers برای existing tools (how to build an MCP server). Give the agent your documents through a retrieval tool (how to build a RAG app).

Step 6: Add guardrails

Agents act in the real world, so safety is part of the design:

  • Separate read and write tools. Reading can run freely; writing, sending, paying or deleting needs human approval.
  • Limits: maximum steps, time and spend per task.
  • Prompt injection: web pages and emails can contain hidden instructions. Treat tool results as data, never as commands.
  • Audit logs: record every step, tool call and result.

Step 7: Evaluate the agent

Create 15–30 realistic tasks with clear success criteria. For each run, record:

  • did it succeed?
  • how many steps and how much did it cost?
  • where did failures happen? (Read the full trace.)

Re-run the set after every change to prompts, tools or models.

Step 8: Multiple agents (only if needed)

A multi-agent setup uses an orchestrator that delegates to specialist agents, for example one researcher per sub-topic. It helps for broad, parallel tasks but adds cost and complexity. Most production agents are a single agent with good ابزار; start there.

Project ideas

  • A research agent that writes a cited report
  • An inbox helper that drafts replies for approval
  • A support agent that checks orders and drafts answers
  • A data agent that queries a read-only database and makes charts

Learn agents step by step

Our free AI agents roadmap breaks this into six steps with notes, tips and tricks and practice projects. For the full career path, see the AI Engineer roadmap and the AI family tree.

#ai agents#agentic ai#tool calling#mcp#llm#python

پرسش‌های متداول

an AI agent چیست؟

An AI agent is a language model running in a loop with tools. It decides which tool to use, looks at the result and repeats until the task is done, instead of only answering a single question.

Do I need a framework to build an AI agent?

No. A basic agent is a short loop around your model provider's tool-calling API. Build one from scratch first to understand it; frameworks help later with memory, tracing and multi-agent setups.

How do I stop an AI agent from doing something harmful?

Limit what its tools can do, set step and cost limits, treat web and email content as untrusted, and require human approval for any action that sends, pays or deletes.

ادامهٔ مطالعه

این صفحه را به اشتراک بگذارید