59API

← Voltar aos guias

Tool Use and Function Calling: A Practical Guide

API · EN · 2026-09-19

What Tool Use Actually Does

Tool use, also called function calling, lets an AI model request an action from your application instead of inventing an answer. The model does not directly access your database, calendar, payment system, or internal APIs. It reads the tool definitions you provide, decides whether a tool is needed, returns structured arguments, and waits for your code to run the requested action.

This separation matters. A support assistant can look up an order status, for example, but your server still decides which order IDs are valid, which customer data may be returned, and whether an action is allowed. Treat model-generated tool arguments as untrusted input, just as you would browser form data.

A Small Order Lookup Example

For this example, use the OpenAI Python SDK with 59API. 59API provides a low-cost, pay-as-you-go relay for official-quality Claude and GPT models while remaining compatible with OpenAI SDK workflows, Codex, and Claude Code. Set your API key in the API_KEY environment variable, then configure the client with its API base URL.

Client setup: from openai import OpenAI
client = OpenAI(api_key=os.environ["API_KEY"], base_url="https://api.59api.com/v1")

Next, describe a tool with a name, purpose, and JSON Schema parameters. A precise schema improves reliability because it tells the model exactly which fields it can request.

Tool definition: tools = [{"type": "function", "function": {"name": "get_order_status", "description": "Look up the current status of one customer order.", "parameters": {"type": "object", "properties": {"order_id": {"type": "string", "description": "The order identifier, such as ORD-1042."}}, "required": ["order_id"], "additionalProperties": false}}}]

Keep functions narrow. A tool named get_order_status should retrieve data only; do not quietly combine lookup, refund, cancellation, and address changes in one broad function. Separate, focused tools are easier to authorize, test, audit, and explain to users.

The Function-Calling Loop

Send the user question and tool list to the model. If it can answer without external data, it returns normal text. If it needs an order lookup, inspect its tool calls, validate each argument, execute the local function, and send the result back to the model.

Request: messages = [{"role": "user", "content": "Where is order ORD-1042?"}]
response = client.chat.completions.create(model="gpt-4.1-mini", messages=messages, tools=tools, tool_choice="auto")
assistant_message = response.choices[0].message

When assistant_message.tool_calls is present, parse the JSON arguments. In production, validate that the order ID matches your expected format and confirm that the authenticated customer owns the order. Do not rely on the model to enforce either rule.

Execution: import json
for call in assistant_message.tool_calls:
  args = json.loads(call.function.arguments)
  order_id = args["order_id"]
  if not order_id.startswith("ORD-"):
    raise ValueError("Invalid order ID")
  result = {"order_id": order_id, "status": "Shipped", "tracking_url": "https://example.com/track/ORD-1042"}

Append the assistant message and a tool-result message to the conversation, then call the model again. The second call converts structured data into a useful answer such as: “Order ORD-1042 has shipped and is available for tracking.” Your application remains the source of truth; the model handles language, intent detection, and response composition.

Production Rules That Prevent Failures

Costs can grow quickly when an agent makes repeated calls, so select an appropriate model for each step and keep tool responses compact. 59API is useful here because developers can access Claude models, including Opus, Sonnet, Haiku, and Fable, alongside GPT models through a compatible endpoint without paying for unused capacity. Its pay-as-you-go pricing and referral rebate also make experimentation and production iteration easier to budget.

Start with one read-only tool, test both expected and malformed requests, then add capabilities gradually. Sign up for 59API when you are ready to connect your existing SDK workflow to affordable model access.

Preços · Docs

Pronto para começar?

Conecte Claude e GPT em minutos pelos menores preços, sem cortes. Cadastre-se e obtenha sua chave API.

Cadastro grátis