AIYINGFrom AI Awareness to Accomplishment
Showing posts with label Function Calling. Show all posts
Showing posts with label Function Calling. Show all posts

Thursday, November 12, 2026

AI Engineering Active Concepts #008 — Tool Calling: Connecting AI Models to Real-World Actions

AI ENGINEERING — ACTIVE CONCEPTS & PRACTICES | #008

Tool Calling: Connecting AI Models to Real-World Actions



Chapter 2: Engineering AI Applications and Agents

AIYING — Accomplishing with AI

The Big Idea: A language model can generate a proposed action, but an application must execute that action through an authorized tool.

Tool calling connects language-model reasoning and interpretation with APIs, databases, enterprise software, and operational workflows.

Engineering question: How do we allow AI systems to use external capabilities without surrendering control over what they can do?

Contents

  1. Why Tool Calling Matters
  2. UNDERSTAND — The Concept
  3. CONNECT — The AI Engineering Ecosystem
  4. The Tool Calling Lifecycle
  5. APPLY — Enterprise Procurement Assistant
  6. Worked Example: Purchase Order Status
  7. Engineering Decisions and Trade-offs
  8. Active Industry Practices
  9. ACCOMPLISH — Practical Exercise
  10. Student and Practitioner Project
  11. Check Your Understanding
  12. Active Connections
  13. References and Further Reading

1. Why Tool Calling Matters

Imagine a procurement manager asking an AI assistant:

"Check purchase order PO-1048. If delivery is delayed, prepare a supplier follow-up."

A conventional chatbot might explain how to check a purchase order manually.

A tool-enabled AI application can retrieve current order information from an authorized enterprise system and prepare a follow-up based on the result.

However, generating a tool call is not the same as executing it.

The application must validate the request, enforce permissions, invoke the tool, inspect the result, and decide whether further action is appropriate.

Tool calling turns AI from a system that only generates responses into a component that can participate in controlled business workflows.

↑ Back to Contents

2. UNDERSTAND — The Concept

What is tool calling?

Tool calling is a mechanism through which an AI model produces a structured request for an external capability made available by an application.

A tool might be a function, API endpoint, database query, search service, calculator, or enterprise workflow operation.

The application typically executes the requested operation and returns the result to the model or workflow controller.

Three essential components

ComponentResponsibility
AI modelInterprets the request and proposes a tool call with arguments
Application or orchestratorValidates, authorizes, executes, and monitors tool operations
External toolPerforms the actual lookup, computation, or authorized action

Common categories of tools

  • Information retrieval: Search knowledge bases or enterprise records.
  • Computation: Calculate values or transform data.
  • Read-only operations: Retrieve order status or inventory levels.
  • Write operations: Create tickets, update records, or schedule tasks.
  • Communication: Prepare or send messages through approved services.
  • Workflow operations: Initiate controlled business processes.

Tool calling versus structured outputs

Structured outputs define the format of model-generated data.

Tool calling uses structured arguments to request a specific external operation.

The two concepts are related, but tool calling introduces additional requirements involving execution, permissions, errors, and external side effects.

Tool calling versus an AI agent

Tool calling is a capability. An AI agent is an application architecture that may use tools, state, planning, and repeated decisions to pursue a task.

A single tool call does not automatically make an application an autonomous agent.

↑ Back to Contents

3. CONNECT — The AI Engineering Ecosystem

Connected ConceptRelationship
Structured OutputsDefines machine-readable tool arguments
JSON SchemaSpecifies required parameters and permitted types
Context EngineeringProvides the tool descriptions and task context
APIsExpose external software capabilities
AI AgentsCoordinate tool use across multiple steps
Workflow StateRecords completed actions and pending operations
MCPStandardizes ways for applications to discover and use external tools and context
ObservabilityRecords execution outcomes, latency, and failures
EvaluationTests tool selection, argument accuracy, and task completion
Security and GovernanceEnforce permissions, approval requirements, and accountability

Active connection: Tool calling brings together model capabilities and conventional software engineering disciplines.

↑ Back to Contents

4. The Tool Calling Lifecycle

User Request

↓

Model Receives Available Tool Definitions

↓

Model Proposes Tool and Arguments

↓

Application Validates and Authorizes

↓

Tool Executes

↓

Application Receives Result

↓

Model or Workflow Processes Result

↓

Verified Response or Next Authorized Action

Step 1 — Register tool definitions

The application describes the available tools, including their names, purposes, and input schemas.

Step 2 — Interpret the user request

The model determines whether a tool is useful and, where supported, produces structured arguments.

Step 3 — Validate and authorize

The application checks argument types, user permissions, allowed operations, and business constraints.

Step 4 — Execute the operation

The application invokes the tool using appropriate credentials and error handling.

Step 5 — Process the result

The result is checked and returned to the model or orchestration logic.

Step 6 — Respond or continue

The system reports the outcome or requests another authorized operation.

Tool results are external data, not automatically trusted instructions.

↑ Back to Contents

5. APPLY — Enterprise Procurement Assistant

Scenario: Purchase Order Follow-Up

A manufacturing company manages hundreds of purchase orders across suppliers.

Procurement teams need to identify delays and coordinate follow-up actions.

A user asks:

"Check PO-1048. If the shipment is delayed, prepare a follow-up task for the procurement team."

Approach A — Conversational assistant

The AI explains how to check an ERP system and create a follow-up task.

The user must complete the steps manually.

Approach B — Tool-enabled assistant

The application exposes two authorized tools:

  • get_purchase_order: Retrieves current purchase-order information.
  • create_followup_task: Creates a procurement task after validation and required approval.

The assistant retrieves the order status, checks whether a delay is indicated, and prepares a task request.

The application determines whether the task may be created automatically or requires human confirmation.

Engineering outcome

Tool calling can reduce manual navigation between systems and support more responsive workflows.

But reliable implementation requires accurate records, access control, approval policies, and confirmation of actual tool execution.

↑ Back to Contents

6. Worked Example: Purchase Order Status

The following is a fictional demonstration. No real ERP system is accessed.

Tool definition

{
  "name": "get_purchase_order",
  "description": "Retrieve an authorized purchase order",
  "parameters": {
    "type": "object",
    "properties": {
      "po_id": {"type": "string"}
    },
    "required": ["po_id"],
    "additionalProperties": false
  }
}

This is a conceptual tool definition. Provider-specific APIs may require a different wrapper or additional fields.

Model-generated tool request

{
  "name": "get_purchase_order",
  "arguments": {
    "po_id": "PO-1048"
  }
}

Illustrative tool response

{
  "po_id": "PO-1048",
  "supplier": "Example Components Ltd",
  "status": "delayed",
  "expected_delivery": "2026-11-18",
  "revised_delivery": "2026-11-23"
}

Next proposed action

The application may prepare a follow-up task based on the confirmed order status.

{
  "name": "create_followup_task",
  "arguments": {
    "po_id": "PO-1048",
    "reason": "Delivery delayed",
    "assigned_team": "procurement"
  }
}

The application must verify authorization and any approval requirement before executing this write operation.

Possible final response

"PO-1048 is marked delayed. The expected delivery date changed from 18 November to 23 November 2026. A procurement follow-up task has been prepared and is awaiting approval."

Important distinction: The assistant must not claim that a task was created unless the external system confirms successful creation.

↑ Back to Contents

7. Engineering Decisions and Trade-offs

DecisionPotential BenefitRisk or Trade-off
Expose more toolsBroader functionalityGreater selection complexity and attack surface
Read-only toolsLower operational riskLimited ability to complete workflows
Write-enabled toolsGreater automationPossibility of unintended changes
Automatic executionLower latencyReduced opportunity for human intervention
Approval gatesStronger controlAdditional workflow time
Parallel tool callsFaster independent operationsConcurrency and dependency complexity
RetriesRecovery from transient failuresDuplicate side effects without safeguards
Detailed loggingAuditability and debuggingStorage and sensitive-data exposure risks

Important failure modes

  • Incorrect tool selection
  • Invalid or invented arguments
  • Unauthorized access to external data
  • Prompt injection through tool results
  • Duplicate write operations after retries
  • Partial completion of multi-step workflows
  • Stale or inconsistent external information
  • False claims of successful execution

Recommended controls

  • Least-privilege credentials and user-scoped authorization
  • Schema and business-rule validation
  • Human approval for consequential actions
  • Timeouts, bounded retries, and rate limits
  • Idempotency keys where supported for write operations
  • Audit logs with appropriate sensitive-data protection
  • Verification of actual execution results
  • Clear separation between untrusted tool content and instructions
The model may propose an action. The application must remain responsible for deciding whether, how, and when it is executed.

↑ Back to Contents

8. Active Industry Practices

Established practices

  • Function and tool calling through model APIs
  • JSON-schema-based argument definitions
  • Integration with enterprise APIs
  • Application-side validation and execution
  • Tool error handling and execution logging
  • Human approval for sensitive operations

Evolving practices

  • MCP-based tool integration
  • Dynamic tool discovery and selection
  • Multi-step agent orchestration
  • Tool execution sandboxing
  • Fine-grained policy enforcement
  • Tool-use evaluation and trace analysis

Industry applications

Tool calling is used in customer support, software development, financial operations, procurement, enterprise search, data analysis, scheduling, and workflow automation.

Practice status: Established AI application capability with rapidly evolving protocols and orchestration practices.

Reviewed: November 2026.

↑ Back to Contents

9. ACCOMPLISH — Practical Exercise

Exercise: Design a Tool-Enabled Procurement Assistant

Use the following fictional purchase-order information:

PO: PO-2056

Supplier: Example Industrial Supplies

Status: Delayed

Original delivery: 20 November 2026

Revised delivery: 26 November 2026

Your tasks

  1. Define a read-only tool to retrieve purchase-order information.
  2. Specify its required input arguments.
  3. Design an illustrative tool response.
  4. Define a second tool for preparing follow-up tasks.
  5. Identify which operation requires authorization or approval.
  6. Describe how the application handles a failed tool call.
  7. Explain how duplicate task creation should be prevented.
  8. Prepare a final user response that accurately reflects the execution status.

Reusable AI-assisted prompt

Act as an AI application engineer.

Design a tool-calling workflow for an
enterprise procurement assistant.

The user wants to check a purchase order
and prepare a follow-up if delivery is delayed.

Provide:
1. Required tools and descriptions.
2. JSON input schemas.
3. Example tool requests and responses.
4. Validation and authorization checks.
5. Human approval requirements.
6. Failure and retry handling.
7. Audit information to capture.
8. A safe final user response.

Use fictional data.
Do not claim that any external action
has actually been executed.

Accomplishment: Design a controlled tool-calling workflow that separates model decisions from authorized software execution.

↑ Back to Contents

10. Student and Practitioner Project

Mini Project: Tool-Enabled Procurement Assistant

Objective: Prototype an AI application that retrieves purchase-order data and prepares follow-up tasks using simulated tools.

Project requirements

  1. Create a fictional purchase-order dataset.
  2. Define two or three tools with input schemas.
  3. Implement a read-only purchase-order lookup.
  4. Implement a simulated task-creation operation.
  5. Validate tool arguments before execution.
  6. Introduce approval checks for write operations.
  7. Simulate timeouts and invalid arguments.
  8. Prevent duplicate task creation during retries.
  9. Record tool calls, outcomes, and execution status.
  10. Evaluate the system using representative user requests.

Suggested evaluation measures

MetricWhat It Measures
Tool selection accuracyWhether the appropriate tool is chosen
Argument accuracyWhether tool parameters match the request
Authorization complianceWhether prohibited operations are blocked
Task completion rateWhether authorized tasks finish successfully
Duplicate action rateWhether retries cause repeated side effects
Execution latencyTime spent invoking and processing tools
Outcome reporting accuracyWhether responses match actual tool results

Deliverable: A working prototype or design, tool definitions, sample execution traces, test results, and a short engineering recommendation.

↑ Back to Contents

11. Check Your Understanding

  1. What is tool calling in an AI application?
  2. Who actually executes a model-proposed tool call?
  3. How is tool calling different from structured outputs?
  4. Why does a tool-enabled application need authorization checks?
  5. What is the difference between read-only and write-enabled tools?
  6. Why are retries risky for operations with side effects?
  7. How does MCP relate to tool integration?
  8. How would you evaluate tool-calling reliability?

Reflection: If an AI assistant correctly identifies a delayed order but the task-creation API fails, what should the assistant tell the user?

↑ Back to Contents

12. Active Connections

Coming next — #009: Model Context Protocol (MCP): Standardizing AI Connections to Tools and Data.

↑ Back to Contents

13. References and Further Reading

  1. OpenAI — Function Calling
  2. OpenAI — Structured Outputs
  3. Model Context Protocol — Introduction
  4. Anthropic — Tool Use
  5. OWASP — Security Risks for LLM Applications

Tool-calling APIs, provider-specific schemas, and integration protocols evolve. Verify current documentation before production implementation.


Final Takeaway

Tool calling connects AI reasoning with real-world capabilities. Reliable engineering ensures that every proposed action is validated, authorized, executed safely, and reported accurately.

AI Engineering — Active Concepts & Practices
Active Concept #008 — Tool Calling

AIYING — Accomplishing with AI

Understand → Connect → Apply → Accomplish

AI Engineering Active Concepts #007 — Structured Outputs: Making AI Responses Machine-Readable and Reliable

AI ENGINEERING — ACTIVE CONCEPTS & PRACTICES | #007

Structured Outputs: Making AI Responses Machine-Readable and Reliable



Chapter 2: Engineering AI Applications and Agents

AIYING — Accomplishing with AI

The Big Idea: AI applications need more than fluent answers. They need outputs that software can interpret, validate, and use consistently.

Structured outputs help transform generative AI from a conversational capability into a component of operational software systems.

Engineering question: How can we turn an AI-generated response into dependable application data?

Contents

  1. Why Structured Outputs Matter
  2. UNDERSTAND — The Concept
  3. CONNECT — Related AI Engineering Concepts
  4. The Structured Output Pipeline
  5. APPLY — Food Quality Inspection Workflow
  6. Worked Example: From Text to JSON
  7. Engineering Decisions and Trade-offs
  8. Active Industry Practices
  9. ACCOMPLISH — Practical Exercise
  10. Student and Practitioner Project
  11. Check Your Understanding
  12. Active Connections
  13. References and Further Reading

1. Why Structured Outputs Matter

Imagine an AI assistant reviewing food manufacturing quality inspection reports.

An inspector writes:

"Batch B204 was inspected at 09:30. Packaging seal integrity failed on three samples. The batch has been placed on hold pending QA review."

A generative AI model might respond:

"The inspection identified three failed packaging seals, and the batch should remain on hold for quality review."

This response is understandable to a human.

But what if an application must automatically populate a database, create a review task, or display the findings on a dashboard?

The software needs clearly defined fields such as batch ID, inspection time, defect category, affected samples, and review status.

A free-form paragraph does not reliably provide those fields.

Structured outputs create a predictable interface between generative AI and conventional software.

↑ Back to Contents

2. UNDERSTAND — The Concept

What are structured outputs?

Structured outputs are AI-generated responses organized according to a predefined data format or schema.

Common formats include JSON objects, typed records, and application-specific data structures.

A schema specifies the expected fields, data types, allowed values, and sometimes additional constraints.

Three levels of output control

ApproachWhat It ProvidesLimitation
Prompt instructionsRequests a specific formatThe model may not consistently comply
JSON modeHelps produce syntactically valid JSONDoes not necessarily enforce a particular schema
Schema-constrained outputConstrains generation to a supported schemaSchema compliance does not guarantee factual accuracy

Capabilities differ across providers, models, and APIs. Some support strict schema-constrained generation, while others require validation and repair after generation.

What is a schema?

A schema is a contract describing the structure of data.

For example, a quality inspection record might require:

  • batch_id: string
  • defect_type: string
  • failed_samples: integer
  • batch_status: defined category
  • review_required: boolean

Four distinct levels of correctness

  1. Syntax: Is the output valid JSON?
  2. Schema: Does it contain the correct fields and types?
  3. Semantic validity: Do the values make sense under business rules?
  4. Factual accuracy: Are the values supported by the original evidence?

A response can pass the first two checks and still contain an incorrect batch number or invented inspection result.

Important: Structured outputs improve format reliability, not truthfulness by themselves.

↑ Back to Contents

3. CONNECT — Related AI Engineering Concepts

ConceptConnection to Structured Outputs
Prompt EngineeringCommunicates extraction rules and task instructions
Context EngineeringSupplies the source information required for accurate output
JSON SchemaDefines permitted data structures and constraints
Type SystemsSupports predictable integration with application code
Function CallingUses structured arguments to invoke tools and APIs
Workflow AutomationConsumes validated data for subsequent operations
AI AgentsExchange structured results between steps and tools
EvaluationMeasures schema adherence and extraction accuracy
ObservabilityTracks validation failures and output quality
AI GovernanceDefines approval, traceability, and accountability requirements

Structured output versus tool calling

Structured output specifies the format of a model's response.

Tool calling allows a model to propose or request an operation using structured arguments, depending on the application's architecture.

The two capabilities are related but not identical. A valid structured tool call must still be authorized, validated, and executed by application logic.

↑ Back to Contents

4. The Structured Output Pipeline

Source Document or User Input

↓

Task Instructions + Output Schema

↓

Generative AI Model

↓

Structured Response

↓

Schema and Business-Rule Validation

↓

Evidence Verification / Human Review

↓

Approved Application Action

Step 1 — Define the data contract

Specify required fields, types, enumerations, and missing-value handling.

Step 2 — Supply reliable source information

Provide the text or retrieved evidence from which the output should be derived.

Step 3 — Generate structured data

Use schema-constrained generation when supported, or a suitable generation-and-validation workflow.

Step 4 — Validate the response

Check types, required fields, permissible values, and application rules.

Step 5 — Verify critical facts

Compare extracted values with source records and identify uncertainty.

Step 6 — Perform authorized actions

Only validated and appropriately approved data should trigger consequential downstream operations.

↑ Back to Contents

5. APPLY — Food Quality Inspection Workflow

Scenario: AI-Assisted Quality Documentation

A food manufacturing organization receives inspection reports from production facilities.

These reports contain batch identifiers, inspection findings, deviations, and recommended follow-up actions.

The organization wants an AI application to extract structured findings and prepare quality review records.

Approach A — Free-form extraction

The model produces a narrative summary.

Employees must manually locate relevant values and enter them into the quality management system.

Different responses may use inconsistent terminology or omit required fields.

Approach B — Structured extraction

The engineering team defines a quality inspection schema.

The AI application extracts fields into a predictable representation.

Validation checks identify missing or invalid values.

Uncertain or critical findings are routed to qualified personnel for verification.

Engineering outcome

The system can reduce repetitive data entry and improve consistency, provided extracted information is verified and workflow controls remain in place.

For regulated quality processes, a schema-valid response must not be treated as automatically approved evidence.

↑ Back to Contents

6. Worked Example: From Text to JSON

Original inspection note

Batch B204 was inspected at 09:30. Packaging seal integrity failed on three samples. The batch has been placed on hold pending QA review.

Illustrative structured response

{
  "batch_id": "B204",
  "inspection_time": "09:30",
  "defect_type": "seal_integrity",
  "failed_samples": 3,
  "batch_status": "on_hold",
  "review_required": true,
  "confirmed_cause": null
}

The null value indicates that the cause has not been established from the supplied note.

Illustrative JSON Schema

{
  "type": "object",
  "properties": {
    "batch_id": {
      "type": "string"
    },
    "inspection_time": {
      "type": "string",
      "pattern": "^([01][0-9]|2[0-3]):[0-5][0-9]$"
    },
    "defect_type": {
      "type": "string"
    },
    "failed_samples": {
      "type": "integer",
      "minimum": 0
    },
    "batch_status": {
      "type": "string",
      "enum": ["on_hold", "released", "rejected"]
    },
    "review_required": {
      "type": "boolean"
    },
    "confirmed_cause": {
      "type": ["string", "null"]
    }
  },
  "required": [
    "batch_id",
    "inspection_time",
    "defect_type",
    "failed_samples",
    "batch_status",
    "review_required",
    "confirmed_cause"
  ],
  "additionalProperties": false
}

This is a general JSON Schema example. Some model APIs support only a subset of JSON Schema features. Adjust the schema to the selected provider's documented requirements.

What does validation catch?

Potential ErrorValidation Response
Missing batch IDRequired-field failure
"three" instead of integer 3Type validation failure
Unknown status valueEnumeration failure
Negative failed-sample countRange validation failure
Invented cause of failureRequires evidence verification; may pass schema checks

The final example demonstrates why schema validation and factual verification must remain separate.

↑ Back to Contents

7. Engineering Decisions and Trade-offs

DecisionPotential BenefitTrade-off
Strict schemaPredictable integrationLess flexibility for unexpected information
Optional fieldsHandles incomplete sourcesMore downstream missing-value logic
Enumerated valuesConsistent classificationsMay exclude legitimate new categories
Automatic retriesCan recover from transient failuresAdditional cost and latency
Human reviewOversight of critical recordsAdditional operational effort
Detailed schemasStronger data contractsMaintenance and versioning complexity
Automatic downstream actionsFaster workflowsGreater consequences from incorrect data

Important failure modes

  • Schema-valid but factually incorrect values
  • Unsupported or invented information
  • Incorrect classification of ambiguous records
  • Missing-value handling failures
  • Schema changes that break downstream integrations
  • Untrusted source text attempting to override instructions
  • Unauthorized actions triggered by extracted data
The strongest data contract is not a substitute for evidence verification, business validation, and authorization.

↑ Back to Contents

8. Active Industry Practices

Established practices

  • JSON-based application integration
  • Schema-constrained model responses
  • Typed data validation
  • Structured tool arguments
  • Application-level business-rule checks
  • Human review for consequential decisions

Evolving practices

  • Schema-first AI application development
  • Typed interfaces between agent components
  • Automated schema-conformance evaluation
  • Versioned contracts for multi-agent systems
  • Structured multimodal information extraction
  • Adaptive validation and exception routing

Where structured outputs are used

Structured outputs support invoice processing, document intelligence, customer-support ticket classification, enterprise workflows, software development assistants, information extraction, and agent orchestration.

Practice status: Established software integration approach with expanding generative AI support.

Reviewed: November 2026.

↑ Back to Contents

9. ACCOMPLISH — Practical Exercise

Exercise: Turn an Inspection Note into Validated Data

Use the following fictional note:

Batch F318 was inspected at 14:15. Two packages showed incorrect labeling. The batch is on hold. The cause has not been confirmed. QA review is required.

Your tasks

  1. Identify the information that should be extracted.
  2. Define a JSON structure for the inspection record.
  3. Identify required and optional values.
  4. Specify permitted batch-status values.
  5. Represent the unconfirmed cause without inventing one.
  6. Generate a structured response using an AI tool.
  7. Validate its fields and types.
  8. Compare every extracted value with the original note.

Reusable AI-assisted prompt

Act as an AI information extraction engineer.

Extract a structured inspection record
from the source note below.

Return only a JSON object with these fields:
batch_id, inspection_time, defect_type,
failed_samples, batch_status,
review_required, confirmed_cause.

Rules:
1. Use only information in the source.
2. Do not invent missing values.
3. Use null for unknown values.
4. Use integers for numerical counts.
5. Use booleans for true/false fields.
6. Flag ambiguity for human review.
7. Do not infer a root cause.

Source note:
[PASTE INSPECTION NOTE]

Accomplishment: Produce a structured inspection record and explain how you would validate it before allowing downstream use.

↑ Back to Contents

10. Student and Practitioner Project

Mini Project: AI Quality Report Extractor

Objective: Build or prototype an application that converts inspection notes into validated structured records.

Project requirements

  1. Create 20 fictional inspection reports with varied wording.
  2. Define a JSON Schema for the target records.
  3. Build a structured extraction workflow.
  4. Validate every generated record.
  5. Compare extracted fields with manually prepared reference answers.
  6. Test missing values, ambiguous language, and conflicting statements.
  7. Record validation failures and extraction errors.
  8. Route uncertain records to a simulated human-review queue.
  9. Estimate processing latency and token consumption.
  10. Document recommendations for safe production integration.

Suggested evaluation measures

MetricWhat It Measures
Schema adherence ratePercentage of responses matching the defined schema
Field accuracyPercentage of extracted fields matching reference values
Missing-value accuracyCorrect handling of unavailable information
Unsupported-value rateFrequency of values not supported by the source
Review-routing accuracyWhether uncertain cases are correctly flagged
LatencyTime needed to process a report

Deliverable: A working prototype or design, sample structured records, validation results, and a short engineering recommendation.

↑ Back to Contents

11. Check Your Understanding

  1. Why are free-form AI responses difficult to integrate into software workflows?
  2. What is the difference between JSON validity and schema validity?
  3. Can a schema-valid response still be factually incorrect?
  4. How should missing information be represented?
  5. How are structured outputs related to function calling?
  6. What is the role of business-rule validation?
  7. Why should critical decisions require appropriate oversight?
  8. How would you evaluate a structured extraction application?

Reflection: If an AI model generates perfectly formatted JSON containing one incorrect batch identifier, has the structured-output system succeeded? Which checks would reveal the problem?

↑ Back to Contents

12. Active Connections

Coming next — #008: Tool Calling: Connecting AI Models to Real-World Actions.

↑ Back to Contents

13. References and Further Reading

  1. OpenAI — Structured Outputs
  2. JSON Schema — Getting Started
  3. Pydantic — Data Validation
  4. OpenAI — Function Calling

API capabilities and supported schema features vary. Consult current provider documentation before implementation.


Final Takeaway

Structured outputs make AI responses usable by software. Reliable AI engineering adds validation, evidence checking, and appropriate authorization before those responses become operational actions.

AI Engineering — Active Concepts & Practices
Active Concept #007 — Structured Outputs

AIYING — Accomplishing with AI

Understand → Connect → Apply → Accomplish

AI Engineering Living Glossary #013 — Tool Calling: Connecting AI Models to External Capabilities

AI ENGINEERING | LIVING GLOSSARY | #013

TOOL CALLING

Connecting AI Models to External Capabilities



Chapter 3: Connecting AI to Tools, Workflows, and Agents

AIYING — Accomplishing with AI

A customer asks an AI assistant:

"Where is my order ORD-1042? Has it been shipped?"

A language model may explain how order tracking normally works. But it cannot know the current status of this particular order unless the relevant information is available to it.

What if the AI application could securely query the company's order management system?

Instead of guessing, the model could request a tool operation, receive the result, and explain the actual status.

This capability is called tool calling, often also called function calling.

Engineering insight: Tool calling connects model-generated requests to external capabilities. The application remains responsible for authorization, execution, validation, and handling results.

1. What Is Tool Calling?

Tool calling is a mechanism through which an AI model produces a structured request to use a capability made available by its host application.

Tools may provide access to:

  • Application functions
  • External APIs
  • Databases and search systems
  • Calculators and computation services
  • Enterprise applications
  • File-processing utilities
  • Business workflow operations

The model typically selects a tool and generates arguments according to a declared interface or schema.

The application then determines whether and how to execute the request.

Crucially, the model does not necessarily execute the tool itself. It proposes a call that an application or runtime may execute after appropriate checks.

↑ Back to contents

2. Why Tool Calling Matters

Language models are powerful at interpreting requests and generating responses, but many useful tasks require access to external information or systems.

Without tool callingWith tool calling
AI explains how to check an order.AI can request the current order status.
AI describes how to calculate a tax.AI can invoke a calculation service.
AI drafts a support ticket.AI can request ticket creation through an authorized API.
AI suggests a calendar event.AI can propose creating an event through a calendar integration.
AI explains inventory management.AI can query an authorized inventory system.

Tool calling helps bridge the gap between generating useful language and interacting with operational systems.

However, connecting tools also introduces security, authorization, data quality, and reliability challenges.

↑ Back to contents

3. How Tool Calling Works

User Request
      |
      v
AI Model Receives Tool Definitions
      |
      v
Model Selects Tool and Arguments
      |
      v
Application Validates Request
      |
      v
Authorization and Policy Checks
      |
      v
Tool Executes
      |
      v
Application Receives Tool Result
      |
      v
Model Interprets Result
      |
      v
Response to User

This is a common pattern, not a universal implementation. Some systems use multiple tool calls, parallel operations, or additional approval checkpoints.

The tool response becomes additional information that the model can use to produce a final answer.

Engineers must distinguish three stages:

  1. Selection: Which tool does the model request?
  2. Execution: What does the authorized application actually do?
  3. Interpretation: How does the model use the returned information?

Each stage can fail independently and should be tested.

↑ Back to contents

4. Core Components of Tool Calling

A. Tool definition

Describes a capability available to the model, including its purpose and required parameters.

B. Tool schema

Defines the expected structure and data types of tool arguments.

C. Tool selection

The model determines whether a tool is relevant to the request.

D. Argument generation

The model generates structured arguments, often represented as JSON.

E. Validation

The application checks argument structure, permitted values, and applicable business requirements.

F. Authorization

The application verifies that the requesting user and executing service are permitted to perform the operation.

G. Execution

The application invokes the underlying function or external service.

H. Result handling

The application receives the result and makes appropriate information available to the model.

I. Error handling

Failures, timeouts, invalid responses, and unavailable services are handled explicitly.

J. Observability

Logs and traces capture relevant operations and outcomes without exposing unnecessary sensitive information.

↑ Back to contents

5. A Practical Tool Call

Consider a fictional tool named get_order_status.

Tool interface

{
  "name": "get_order_status",
  "description": "Retrieve an authorized order status",
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": {
        "type": "string"
      }
    },
    "required": ["order_id"]
  }
}

Model-generated request

{
  "name": "get_order_status",
  "arguments": {
    "order_id": "ORD-1042"
  }
}

The application validates the request and verifies that the authenticated customer is permitted to access this order.

Illustrative tool result

{
  "order_id": "ORD-1042",
  "status": "Shipped",
  "carrier": "Example Logistics",
  "estimated_delivery": "2026-11-15"
}

Assistant response

"Your order ORD-1042 has shipped with Example Logistics. The estimated delivery date is November 15, 2026."

This example uses fictional data and a simplified provider-neutral representation of tool calling.

The important point is that the answer is based on the authorized tool result rather than an invented delivery status.

↑ Back to contents

6. Tool Calling vs RAG and AI Agents

ConceptPrimary purpose
Tool CallingRequest use of an external capability through a defined interface.
RAGRetrieve relevant information to support generation.
WorkflowCoordinate a sequence of operations according to a defined process.
AI AgentPursue goals through model-guided decisions and, often, tool use.

These concepts overlap.

A RAG system may use a retrieval tool. An AI agent may call several tools. A workflow may orchestrate model calls, tools, and deterministic operations.

Tool calling alone does not make an application an autonomous AI agent.

↑ Back to contents

7. Security and Reliability

Tool calling can turn model-generated text into requests with real operational consequences.

That makes independent controls essential.

Least-privilege permissions

Expose only capabilities necessary for the application's intended purpose.

Server-side authorization

Check the authenticated user's permissions before accessing data or executing actions.

Argument validation

Validate types, formats, ranges, and business constraints independently of the model.

Untrusted tool outputs

Treat retrieved text and tool responses as data, not authoritative instructions.

Approval for consequential actions

Require human confirmation where appropriate for payments, deletions, deployments, or other sensitive operations.

Timeouts and retries

Handle unavailable services without creating uncontrolled retry loops.

Idempotency

Protect applicable operations against unintended duplication, especially when retries occur.

Result verification

Distinguish a requested action from an action that was actually completed successfully.

Security principle: A model-generated tool request is not authorization. Trusted application controls must determine whether execution is permitted.
↑ Back to contents

8. Industry Applications

Industry applicationExample tool capability
Customer supportRetrieve order status or create a ticket.
BankingRetrieve permitted account information.
Human resourcesQuery authorized leave balances.
Software engineeringRun tests or inspect repository metadata.
Supply chainQuery inventory and shipment records.
Business analyticsExecute controlled data queries.
Enterprise operationsInteract with approved workflow APIs.

The tool integration must respect the security, privacy, and operational requirements of the particular industry.

↑ Back to contents

9. What Must an AI Engineer Decide?

  1. Which external capabilities should be exposed to the model?
  2. How should each tool be described?
  3. What argument schema is appropriate?
  4. When should tool use be mandatory, optional, or prohibited?
  5. How will user identity and authorization be verified?
  6. Which operations require human approval?
  7. How will invalid tool arguments be handled?
  8. What happens when a service is unavailable?
  9. How will retries avoid duplicate actions?
  10. How will tool responses be validated?
  11. How will failures be logged and investigated?
  12. How will tool-selection accuracy and task success be evaluated?

These are engineering design decisions, not merely prompt-writing choices.

↑ Back to contents

10. Practical Industry Case: The Order That AI Could Actually Track

A retail company deploys an AI customer support assistant.

A customer asks about order ORD-1042.

The assistant has access to a read-only order status tool.

Engineering approach

  1. Identify the customer's request.
  2. Select the appropriate order status tool.
  3. Extract the order identifier.
  4. Validate the identifier format.
  5. Verify the authenticated customer's access to the order.
  6. Call the authorized order management API.
  7. Validate the returned data.
  8. Handle missing orders or service errors.
  9. Generate an answer based on the actual tool result.
  10. Avoid inventing unavailable information.
  11. Record operational telemetry.
  12. Evaluate accuracy, latency, and error handling.

What if the tool fails?

The assistant should not invent a shipment status. It should explain that the current information could not be retrieved and offer an appropriate next step.

What if the customer requests cancellation?

Cancellation is a different capability with different authorization and business requirements. A read-only tracking tool should not be able to cancel an order.

Industry insight: Tool calling is valuable because it connects AI to real information and actions. Its reliability depends on the surrounding engineering controls.

↑ Back to contents

11. Try It Yourself

Mini Project: Design an AI Order Tracking Assistant

Objective: Design and simulate a tool-calling workflow without connecting to a real customer database.

  1. Create a fictional dataset containing five orders.
  2. Define a tool named get_order_status.
  3. Specify its purpose and input schema.
  4. Prepare ten customer questions.
  5. Include valid, invalid, and unauthorized order requests.
  6. Ask an AI model to identify the appropriate tool and arguments.
  7. Validate the generated arguments.
  8. Simulate an authorization check.
  9. Return fictional order data for permitted requests.
  10. Generate customer-facing responses.
  11. Simulate a tool timeout and an unknown order.
  12. Verify that the model does not invent missing results.
  13. Record tool selection, validation, and response outcomes.
  14. Revise the tool description and repeat the experiment.

Suggested evaluation measures

MeasureQuestion
Tool selection accuracyWas the correct tool selected?
Argument validityWere required arguments correctly structured?
Authorization enforcementWere unauthorized requests blocked?
Result fidelityDid the response accurately reflect tool data?
Error handlingWere failures communicated appropriately?
Task successWas the legitimate customer need satisfied?

Reflection questions

  • Why is a tool call different from an ordinary model response?
  • Who is responsible for executing the tool?
  • Why must arguments be validated?
  • What happens if the model selects the wrong tool?
  • How should authorization be enforced?
  • What makes a tool-calling system production-ready?

Success criterion: Produce a working simulation or documented design showing tool definitions, request validation, authorization, execution, response handling, and evaluation.

↑ Back to contents

12. Connected Glossary Terms

  • Token: Tool definitions and returned data contribute to context usage.
  • Prompt Engineering: Instructions help guide appropriate tool selection.
  • RAG: Retrieval can be exposed through tools.
  • Context Window: Large tool results may consume context capacity.
  • Evals: Test tool selection, argument correctness, and task success.
  • Hallucination: Tool results can reduce reliance on unsupported guesses.
  • Grounding: Retrieved tool data can provide evidence for answers.
  • Guardrails: Enforce tool permissions and execution restrictions.
  • Observability: Trace tool calls, failures, and latency.
  • Human-in-the-Loop: Require approval before designated actions.

Previous lesson: #012 — Human-in-the-Loop

Next lesson: #014 — Workflows: Orchestrating Multi-Step AI Processes.

↑ Back to contents

13. Living Update

Editorial baseline: November 2026

Tool calling is an important foundation for modern AI applications and agents.

Areas to monitor include:

  • Structured tool interfaces and schemas.
  • Standardized tool discovery and integration protocols.
  • Model Context Protocol (MCP) adoption and security.
  • Tool selection and argument generation evaluations.
  • Agent tool permissions and authorization.
  • Parallel and multi-step tool execution.
  • Approval checkpoints for consequential operations.
  • Tracing and auditing of tool interactions.

Living Glossary note: Update this entry as tool integration standards, model capabilities, and enterprise security practices evolve.

↑ Back to contents

14. Key Takeaway

Tool calling enables AI applications to request external capabilities, while trusted software remains responsible for deciding what actually executes.

Reliable tool calling requires more than a model that can generate function arguments. It requires secure interfaces, permissions, validation, error handling, and verification.

Think like an AI engineer: When an AI model proposes an action, what ensures that the right tool executes correctly, safely, and only with appropriate authorization?

↑ Back to contents

15. References and Further Reading

↑ Back to contents

AI Engineering — Living Glossary

One Term. One Industry Connection. One Practical Insight. One Action.

AIYING — Accomplishing with AI

Chapter 3 | Episode #013 | TOOL CALLING

↑ Return to top

Monday, November 9, 2026

AI Engineering Principle 004: Make the Tool Obvious

AI Engineering Principles & Practice · Post 004

Make the Tool Obvious

Clear purpose. Clear inputs. Useful results.


The principle

An AI system can only use a tool through the interface it receives. If the tool name is vague, the inputs are unclear, or the result is hard to interpret, the agent may choose the wrong tool or use it incorrectly.

A tool is part of the AI system’s design. Its description should make clear what it does, when it should be used, what information it needs, and what it returns. The system should also handle invalid inputs and errors in a way that makes the next step understandable.

For example, a tool named search gives little guidance. A tool described as “search the official course handbook for course rules and deadlines” gives a clearer signal about its purpose.

Back to top ↑

A practical example: searching a course handbook

Suppose you are building an assistant that answers questions from a course handbook. It has access to a search tool. A useful tool definition could clarify:

  • Purpose: Search the official handbook for course information.
  • When to use it: Use it when an answer depends on handbook content or a course-specific rule.
  • Inputs: A clear search query, and the course identifier if there are multiple handbooks.
  • Results: Relevant passages with section names or page references.
  • No-result behavior: Return a clear “no relevant passage found” result so the assistant knows not to invent an answer.

This helps the agent distinguish a grounded answer from a guess and gives it information it can use in its response.

Back to top ↑

Designing a useful tool

When you design a tool for an AI system, consider these questions:

  1. Does the name make the tool’s purpose clear?
  2. Does the description explain when the tool should—and should not—be used?
  3. Are input names, formats, and required fields understandable?
  4. Does the tool return information in a predictable, useful format?
  5. Do errors explain what went wrong and how the system can recover?

Design the interface, then test it on realistic tasks. A test set can include ordinary requests, ambiguous requests, missing inputs, and cases where the tool should not be called. Review the results and revise the interface when the agent repeatedly misunderstands it.

Engineering takeaway: Design a tool so its purpose, inputs, and results are clear to the agent.

Back to top ↑

Independent study exercise

Design a tool that lets an AI assistant search a course handbook. Write a short specification with:

  • The tool’s name and purpose.
  • When the assistant should use it.
  • The input fields and their formats.
  • The result fields the tool should return.
  • What the tool should return when it finds no relevant information or receives invalid input.

Then try three realistic questions. Check whether the assistant chooses the tool appropriately, supplies usable inputs, and explains the result accurately. Add any recurring failure to your evaluation set.

Back to top ↑

Research basis

  • Anthropic, “Writing Effective Tools for Agents — With Agents” (September 11, 2025). The article discusses clearly defined tools, tool descriptions, realistic evaluation tasks, and iterative improvement.
  • OpenAI, “Function Calling”. The guide recommends clear function names and parameter descriptions, predictable and intuitive functions, and structured inputs that help prevent invalid calls.

This post is an independent study reference based on publicly available engineering material. It is not an official guide or endorsement from the cited organizations.

AIYING — Accomplishing with AI
AI Engineering Principles & Practice · 004

Saturday, October 3, 2026

The Minimalist Function Calling: Function Calling Explained in 100 Words

The Minimalist Function Calling - Function Calling Explained in 100 Words by Ravindra Dastikop

THE MINIMALIST FUNCTION CALLING

Function Calling Explained in 100 Words

Ravindra Dastikop

Understand less. Accomplish more.


Why This Book?

Function calling can sound complicated.

Tools.
Functions.
Schemas.
Arguments.
Selection.
Execution.
Results.
Validation.
Actions.
Judgment.

But using function calling does not have to begin with complexity.

This book strips function calling down to what matters.

10 ideas.
10 words each.
100 words.
Enough to begin.


How to Read This Book

Read one idea.

Stop.

Think about it.

Try it with AI.

Then move to the next.

The purpose is not to know everything about function calling.

The purpose is to understand enough to accomplish something with function calling.


01 — FUNCTION CALLING

Function calling lets AI models request functions using structured arguments.

Normally, a model generates a response.

Function calling gives it another possibility.

Instead of merely describing what should happen, the model can request a function made available by an application.

Imagine asking:

“What is the status of order 4821?”

The model itself may not know.

But an application could provide a function such as:

get_order_status

The model can recognize that the function is useful and request it with the appropriate order number.

The important distinction is:

The model requests the function.

The application executes it.

REQUEST → FUNCTION CALL → APPLICATION

02 — TOOLS

Tools extend models beyond generation by connecting with external capabilities.

Language generation is powerful.

But many useful tasks require capabilities outside the model.

For example:

Retrieve customer information.
Check inventory.
Create a support ticket.
Calculate shipping.
Search company systems.
Update an application.

Function calling allows application-defined functions to become tools available to the model.

This changes the model from something that can only say what should happen into part of a system that can help determine which capability should be used.

MODEL + TOOLS → CAPABILITY

03 — FUNCTIONS

Functions define operations applications make available for models to request.

A function represents something the application knows how to do.

For example:

get_weather
find_customer
check_inventory
create_ticket
calculate_price

Each function should have a clear purpose.

The model needs enough information to understand what the function does and when it is appropriate.

The application decides which functions are available.

The model can determine when an available function may help accomplish the task.

APPLICATION → FUNCTION → MODEL ACCESS

04 — SCHEMAS

Schemas describe function arguments so models can generate structured inputs.

A function needs more than a name.

It needs to describe the information it expects.

Suppose we have:

get_weather

The function might require:

Location.
Unit.
Date.

A schema defines the expected structure of those arguments.

For example:

location → string
unit → Celsius or Fahrenheit

This gives the model a structured contract for constructing the function request.

Clear schemas can make function calls more predictable and easier for applications to process.

FUNCTION → SCHEMA → STRUCTURE

05 — ARGUMENTS

Arguments contain structured values the model supplies when requesting functions.

Once the model chooses a function, it needs to provide the required information.

Consider:

get_weather(location)

If the user asks:

“What is the weather in Bengaluru?”

The model might request the function with:

location = Bengaluru

That value is an argument.

Arguments translate information from the conversation into structured input that application code can use.

This is an important transition.

Natural language becomes machine-processable parameters.

LANGUAGE → ARGUMENTS → FUNCTION REQUEST

06 — SELECTION

Selection determines whether models choose available functions automatically or explicitly.

Giving the model functions does not mean every function must always be used.

Sometimes the model can decide whether a tool is necessary.

Sometimes the application may constrain or specify which function can be called.

Consider:

“Hello.”

No external function may be needed.

But:

“Check whether product X is in stock.”

may require an inventory function.

Function selection therefore connects the user's intention with the capability most appropriate for accomplishing it.

INTENT → SELECT → FUNCTION

07 — EXECUTION

Execution happens in application code after models request function calls.

This distinction is essential.

The model does not automatically execute your application function merely because it generated a function call.

The model produces a request.

Your application receives it.

Your code examines the request.

Then the application executes the corresponding operation.

For example:

Model requests → get_inventory(product_id)

Your application might then query:

A database.
An API.
An enterprise system.
Another service.

The application remains responsible for actually performing the operation.

MODEL REQUESTS → APPLICATION EXECUTES

08 — RESULTS

Results return outputs to models for continued reasoning and responses.

Execution produces something.

Suppose the application checks inventory and receives:

17 units available.

That result can be returned to the model.

The model now has information it did not previously possess.

It can continue the interaction and answer:

“There are currently 17 units available.”

This creates a loop.

The model identifies a need.

It requests a function.

The application executes it.

The result returns.

The model continues.

REQUEST → EXECUTE → RESULT → CONTINUE

09 — VALIDATION

Validation checks model generated arguments before applications perform requested operations.

Function calls are generated by AI.

They should not automatically be treated as trustworthy instructions.

Arguments may be:

Missing.
Incorrect.
Unexpected.
Unauthorized.
Unsafe.
Inconsistent with application rules.

The application should therefore validate inputs before performing operations.

This becomes particularly important when functions can:

Change records.
Send messages.
Spend money.
Delete information.
Access sensitive systems.
Create other real-world consequences.

Function calling connects AI with action.

Validation helps create a boundary before action occurs.

CALL → VALIDATE → EXECUTE

10 — JUDGMENT

Judgment determines which functions, permissions, and actions remain appropriate overall.

Function calling can make AI systems substantially more capable.

But greater capability also creates greater responsibility.

Developers and organizations must decide:

Which functions should exist?
Which functions should the model access?
What permissions should they receive?
Which actions need approval?
What information can functions expose?
Which operations require human confirmation?

The goal is not to give AI every possible capability.

The goal is to provide the right capability with the right boundaries.

AI REQUESTS → SYSTEM CONTROLS → HUMAN JUDGES

The Entire Book in 100 Words

FUNCTION CALLING
Function calling lets AI models request functions using structured arguments.

TOOLS
Tools extend models beyond generation by connecting with external capabilities.

FUNCTIONS
Functions define operations applications make available for models to request.

SCHEMAS
Schemas describe function arguments so models can generate structured inputs.

ARGUMENTS
Arguments contain structured values the model supplies when requesting functions.

SELECTION
Selection determines whether models choose available functions automatically or explicitly.

EXECUTION
Execution happens in application code after models request function calls.

RESULTS
Results return outputs to models for continued reasoning and responses.

VALIDATION
Validation checks model generated arguments before applications perform requested operations.

JUDGMENT
Judgment determines which functions, permissions, and actions remain appropriate overall.


The Minimalist Function Calling

You do not need to understand every function-calling implementation before you begin.

Remember ten things:

Function Calling.

Tools.

Functions.

Schemas.

Arguments.

Selection.

Execution.

Results.

Validation.

Judgment.

Everything else can come later.

Define the capability.

Describe the function.

Create the schema.

Supply the tool.

Let the model select appropriately.

Receive structured arguments.

Validate them.

Execute the function.

Return the result.

Apply human judgment.

Then accomplish something.


One Final Question

The next time you build an AI application, don't begin with:

“What should the model say?”

Begin with:

“What should the model be able to ask my application to do?”

Then give it the right tools.


Accomplish with AI

Powered by Blogger.

Featured post

AI Engineering Hands-On Lab #001 — Build an AI Answer Reliability Test Bench Without Code

AIYING | Daily 24 — Post 009 AI Engineering Hands-On Lab #001 Build an AI Answer Reliability Test Bench — Without Writing Code Lea...

Search This Blog

List of blogs

Search This Blog

About

Translate

Instant Stories

Read in Your Language

Test

share this

ShareThis

Popular Posts