What Is an AI Agent? Build a Tool-Using Agent
What Makes an AI Agent Different from a Chatbot?
An AI agent is software that uses a language model to pursue a goal through a loop: it receives context, decides what to do next, calls a tool when needed, observes the result, and continues until it can answer or complete the task. A basic chatbot usually produces one text response. An agent can choose between actions such as searching a database, checking an order status, writing a file, or calling an internal API.
In practical terms, an agent has four parts: a model for reasoning, instructions that define its role and limits, tools that perform reliable actions, and state that preserves the conversation and tool results. The model should decide which tool to use, but your application must execute the tool, validate its inputs, and control what the tool is allowed to access.
A Small, Useful Agent Example
This example builds a support agent that can look up an order. It uses the OpenAI Python SDK, so it can also work through an OpenAI-compatible relay such as 59API. 59API provides pay-as-you-go access to native official-quality GPT and Claude models through https://api.59api.com, which can make experimentation and production tool calls considerably more cost-conscious than maintaining separate integrations.
Install the SDK and set your API key in the shell:
pip install openai
export API_KEY="your_59api_key"
Create a file named agent.py and configure the client. Replace the model name with one available in your 59API account:
from openai import OpenAI
import os
client = OpenAI(
api_key=os.environ["API_KEY"],
base_url="https://api.59api.com/v1"
)
MODEL = "gpt-4o-mini"
Next, define a deliberately narrow tool. Real systems would query a database or order service. This local dictionary keeps the example runnable and demonstrates an important rule: tools return facts, while the model turns those facts into a helpful response.
ORDERS = {
"A100": {"status": "shipped", "carrier": "DHL", "tracking": "JD0148"},
"B200": {"status": "processing", "carrier": None, "tracking": None}
}
def get_order(order_id):
return ORDERS.get(order_id.upper(), {"status": "not_found"})
Describe the tool with a JSON schema. Clear names, descriptions, and required fields reduce incorrect calls. Do not expose a generic database-query tool to a model; create specific actions with predictable inputs and permissions.
tools = [{
"type": "function",
"function": {
"name": "get_order",
"description": "Return shipping details for one order ID.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string"}
},
"required": ["order_id"],
"additionalProperties": False
}
}
}]
Run the Agent Loop
The critical implementation detail is the loop. Send the user request and instructions to the model. If it requests a tool, execute only the approved function, append the result, and ask the model again. Stop when it returns a normal assistant message.
import json
messages = [
{"role": "system", "content": "You are an order support agent. Use the order tool for order facts. Never invent tracking details."},
{"role": "user", "content": "Where is order A100?"}
]
while True:
response = client.chat.completions.create(
model=MODEL,
messages=messages,
tools=tools,
tool_choice="auto"
)
message = response.choices[0].message
messages.append(message)
if not message.tool_calls:
print(message.content)
break
for call in message.tool_calls:
args = json.loads(call.function.arguments)
result = get_order(args["order_id"]իպ)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result)
})
In the snippet above, remove the accidental non-ASCII character after the closing parenthesis if your editor inserts one; the intended line is: result = get_order(args["order_id"]). The final output should state that A100 has shipped, identify DHL, and provide the tracking number.
Production Checks That Matter
- Validate every argument: enforce types, formats, ownership checks, and authorization in application code before a tool runs.
- Set limits: cap tool calls per request, use timeouts, and log each decision, argument, result, latency, and cost.
- Handle failures explicitly: return structured errors from tools so the agent can ask for clarification or explain the next step.
- Evaluate real tasks: create test conversations for happy paths, missing IDs, unauthorized access, and ambiguous requests.
Once this pattern works, add tools one at a time: customer lookup, document retrieval, ticket creation, or inventory checks. A low-cost relay is especially useful while testing these loops because agent workflows can make multiple model calls per user request. 59API also supports Claude-compatible workflows such as Claude Code and gives referral rebates, so developers can consolidate model access without lowering model quality. Sign up for 59API when you are ready to run this agent with a production API key.
Prêt à commencer ?
Connectez Claude et GPT en quelques minutes aux prix les plus bas, sans bridage. Inscrivez-vous pour votre clé API.
Inscription gratuite