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

Friday, November 13, 2026

AI Engineering Active Concepts #010 — Agent Orchestration: Designing Reliable Multi-Step AI Workflows

AI ENGINEERING — ACTIVE CONCEPTS & PRACTICES | #010

Agent Orchestration: Designing Reliable Multi-Step AI Workflows



Chapter 2: Engineering AI Applications and Agents

AIYING — Accomplishing with AI

The Big Idea: Agent orchestration coordinates the sequence, dependencies, tools, decisions, state, and controls required to complete multi-step AI tasks.

An individual model response may be useful. An orchestrated workflow must deliver a verifiable outcome.

Engineering question: How do we make an AI workflow reliable when it involves multiple steps, external systems, failures, and human approvals?

Contents

  1. Why Agent Orchestration Matters
  2. UNDERSTAND — The Concept
  3. CONNECT — AI Engineering Relationships
  4. Agent Orchestration Architecture
  5. APPLY — Enterprise Procurement Workflow
  6. Worked Example: A Multi-Step Workflow
  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 Agent Orchestration Matters

Consider an enterprise procurement manager asking:

"Check purchase order PO-1048. Verify whether the required material is available elsewhere. If delivery is delayed, recommend a recovery action and prepare the necessary follow-up."

This is not a single question. It is a sequence of dependent tasks.

The AI application may need to retrieve purchase-order information, inspect inventory, compare delivery alternatives, apply procurement policies, prepare a recommendation, and obtain approval before making changes.

Each step depends on information or decisions from previous steps.

What happens if the inventory service is unavailable? What if the purchase-order record is inconsistent? What if a human reviewer rejects the proposed action?

These are orchestration problems.

Agent orchestration is not simply connecting several AI calls. It is engineering the control flow that turns multiple operations into a dependable business outcome.

2. UNDERSTAND — The Concept

What is agent orchestration?

Agent orchestration is the coordination of AI models, tools, workflow steps, decisions, application state, and control mechanisms to accomplish a task.

The orchestrator may be implemented through conventional software logic, a workflow engine, an agent framework, or a combination of these.

Five essential responsibilities

ResponsibilityEngineering Question
PlanningWhich steps are required?
CoordinationWhat should run next, and what depends on what?
State managementWhat has already happened?
ControlWhich operations are permitted?
RecoveryWhat happens when a step fails?

Workflow versus agent

A workflow generally follows a predefined control structure. An agent may dynamically select actions and tools based on intermediate observations.

In practice, production systems often combine both approaches.

For example, an agent may analyze a supplier delay while a deterministic workflow controls approvals, record updates, and completion status.

Common orchestration patterns

  • Sequential: Execute dependent steps in order.
  • Parallel: Run independent operations concurrently.
  • Conditional routing: Choose a branch based on validated results.
  • Iterative: Repeat a bounded process until a condition is satisfied.
  • Supervisor-worker: Delegate specialized tasks to different components.
  • Human-in-the-loop: Pause for an authorized decision.
  • Event-driven: Resume when an external event occurs.

Not every problem needs multiple agents. A deterministic workflow with one model and a few tools may be simpler, cheaper, and easier to test.

3. CONNECT — AI Engineering Relationships

ConceptRelationship to Orchestration
Context EngineeringSupplies relevant information to each step
Token EconomicsControls the cost of repeated model calls
Retrieval EngineeringProvides external evidence
Context ManagementPreserves state and continuity
Structured OutputsDefines data contracts between steps
Tool CallingInvokes external capabilities
MCPProvides standardized access to external capabilities
EvaluationTests both individual steps and overall outcomes
ObservabilityTraces execution, latency, cost, and failures
GovernanceEstablishes accountability and approval controls

Active connection: Orchestration brings together the capabilities studied in earlier lessons into an operational AI application.

4. Agent Orchestration Architecture

User Request

↓

Workflow Controller / Orchestrator

↓

Task Planning and State Initialization

↓

Model and Tool Execution

↓

Result Validation

↓

Decision: Continue, Retry, Escalate, or Stop?

↓

Human Approval When Required

↓

Authorized Business Action

↓

Outcome Verification and Audit Record

State transitions

A workflow should have explicit states, such as:

CREATED
   |
   v
RUNNING
   |
   +--> WAITING_FOR_APPROVAL
   |           |
   |           v
   |        RUNNING
   |
   +--> FAILED
   |
   +--> COMPLETED

Real implementations may need additional states such as cancelled, timed out, rejected, or requiring manual intervention.

Why state matters

State enables a workflow to resume after interruptions, avoid repeating completed actions, and distinguish a pending operation from a successful one.

State should be stored in a durable application system when the workflow must survive process restarts or extended human approval delays.

5. APPLY — Enterprise Procurement Workflow

Scenario: Recovering from a Supplier Delay

A manufacturing company uses an AI assistant to investigate delayed material deliveries.

The assistant has access to fictional procurement, inventory, and supplier systems.

Step 1 — Retrieve purchase order

The system obtains the current order status through an authorized lookup tool.

Step 2 — Check inventory

The application retrieves stock availability from alternative locations.

Step 3 — Evaluate alternatives

The AI analyzes available evidence and prepares possible recovery options.

Step 4 — Apply business constraints

Deterministic checks verify inventory eligibility, policy requirements, and permitted actions.

Step 5 — Request approval

If a transfer or supplier change requires approval, the workflow pauses for the designated decision-maker.

Step 6 — Execute authorized action

The application invokes the approved operation and verifies its result.

Step 7 — Complete and record

The workflow reports the outcome and records the relevant execution history.

Important: The assistant should never describe an operation as completed merely because the model proposed it.

6. Worked Example: A Multi-Step Workflow

The following is a fictional design illustration, not a live enterprise integration.

Sample workflow state

{
  "workflow_id": "WF-1048",
  "po_id": "PO-1048",
  "status": "waiting_for_approval",
  "order_status": "delayed",
  "alternative_stock_available": true,
  "recommended_action": "internal_transfer",
  "approval_status": "pending",
  "execution_status": "not_started"
}

Illustrative orchestration pseudocode

async def process_order(po_id, user):
    order = await get_order(po_id, user)
    validate_order(order)

    if order["status"] != "delayed":
        return {"status": "completed",
                "action": "none"}

    inventory = await check_inventory(order, user)
    validate_inventory(inventory)

    proposal = await recommend_action(
        order, inventory
    )
    validate_proposal(proposal)

    approval_id = await request_approval(
        proposal, user
    )

    # Persist state and stop execution.
    # Resume only after a verified approval event.
    return {
        "status": "waiting_for_approval",
        "approval_id": approval_id,
        "execution_status": "not_started"
    }

This pseudocode illustrates a workflow boundary. A production implementation must authenticate the approver, persist state, resume through a controlled event, enforce authorization, and verify any eventual write operation.

What makes the workflow reliable?

  • Each step has defined inputs and outputs.
  • External results are validated.
  • State is recorded before suspension.
  • Approvals are explicit.
  • Retries are bounded and controlled.
  • Side-effecting actions use duplicate-prevention safeguards.
  • Completion is based on verified execution results.

7. Engineering Decisions and Trade-offs

DecisionBenefitTrade-off
Fixed workflowPredictability and testabilityLess flexibility
Dynamic agent planningAdapts to varied tasksHarder to constrain and evaluate
Parallel executionReduced latencyDependency and concurrency risks
Persistent stateResumabilityStorage and consistency complexity
Automatic retriesFailure recoveryCost and duplicate-action risks
Human approvalStronger oversightAdditional time
Multiple specialized agentsDivision of responsibilitiesCoordination overhead

Common failure modes

  • Infinite or excessive execution loops
  • Incorrect tool selection
  • Loss of workflow state
  • Contradictory intermediate results
  • Repeated actions after retries
  • Unauthorized execution
  • Unbounded token consumption
  • Incorrect completion reporting
  • Prompt injection through retrieved data or tool results

Recommended engineering controls

  • Maximum step and execution budgets
  • Timeouts and bounded retries
  • Checkpointing and durable state
  • Idempotency for operations with side effects
  • Structured contracts between components
  • Explicit approval boundaries
  • Least-privilege tool permissions
  • Execution tracing and audit records
  • Outcome-based evaluations
Reliable orchestration requires a controlled workflow, not merely a capable model.

8. Active Industry Practices

Established engineering approaches

  • State-machine and graph-based workflows
  • Task dependency management
  • Tool execution with validation
  • Human approval checkpoints
  • Persistent workflow state
  • Execution tracing and monitoring

Evolving AI engineering practices

  • Model-directed workflow routing
  • Supervisor and specialist-agent architectures
  • Agent evaluation using execution traces
  • Policy-aware tool orchestration
  • Adaptive planning with bounded autonomy
  • Durable execution for long-running agents

Relevant technologies

Developers may evaluate frameworks such as LangGraph, Microsoft Agent Framework, OpenAI Agents SDK, and conventional workflow engines.

These technologies have different architectures and operational characteristics. Framework selection should follow the requirements of the application rather than determine the architecture in advance.

Industry applications

Agent orchestration is relevant to customer support, software engineering, incident response, research assistants, enterprise operations, procurement, document processing, and multi-step business automation.

Practice status: Established workflow-engineering principles combined with evolving agentic AI architectures.

Reviewed: November 2026.

9. ACCOMPLISH — Practical Exercise

Exercise: Design a Procurement Recovery Workflow

Use this fictional scenario:

Purchase order: PO-2056

Status: Delayed

Required quantity: 500 units

Alternative location stock: 350 units

Proposed action: Partial internal transfer

Approval: Required

Your tasks

  1. Define the workflow objective.
  2. List the required tools and data sources.
  3. Identify sequential and parallel steps.
  4. Define workflow states and transitions.
  5. Specify validation checkpoints.
  6. Identify actions requiring approval.
  7. Design failure and retry handling.
  8. Define completion and escalation conditions.
  9. Explain how the remaining 150-unit shortage will be handled.

Reusable AI-assisted prompt

Act as an enterprise AI workflow architect.

Design an agent orchestration workflow
for a delayed purchase order.

Scenario:
- Order: PO-2056
- Required quantity: 500 units
- Alternative stock: 350 units
- Supplier delivery: delayed
- Internal transfer: approval required

Provide:
1. Workflow objective.
2. Required tools and data.
3. Step-by-step execution plan.
4. State transitions.
5. Validation rules.
6. Approval checkpoints.
7. Failure recovery strategy.
8. Cost and execution limits.
9. Observability requirements.
10. Completion and escalation criteria.

Distinguish AI-generated recommendations
from verified system actions.

Do not claim any real action was executed.

Accomplishment: Produce an orchestration design that can be reviewed for reliability, authorization, recovery, and measurable completion.

10. Student and Practitioner Project

Mini Project: Build a Stateful Procurement Agent

Objective: Prototype a multi-step AI workflow using simulated enterprise systems.

Project requirements

  1. Create fictional purchase-order and inventory datasets.
  2. Define lookup and simulated action tools.
  3. Implement a workflow controller.
  4. Persist workflow state between steps.
  5. Use structured inputs and outputs.
  6. Introduce an approval checkpoint.
  7. Simulate a tool timeout and a service failure.
  8. Test workflow resumption after interruption.
  9. Prevent duplicate side effects.
  10. Record execution traces and evaluate outcomes.

Suggested evaluation metrics

MetricWhat It Measures
Task completion rateSuccessful completion of authorized workflows
Step accuracyCorrect execution of required stages
Recovery successResumption after failures
State consistencyCorrectness of persisted workflow information
Approval complianceWhether required approvals are enforced
Duplicate action rateRepeated side effects after retries
Execution costModel and tool resource consumption
End-to-end latencyTotal workflow processing time

Project deliverable: A workflow diagram, working prototype or design, sample execution traces, evaluation results, and an engineering recommendation.

11. Check Your Understanding

  1. What is agent orchestration?
  2. How is orchestration different from tool calling?
  3. What is the difference between a fixed workflow and a dynamic agent?
  4. Why is persistent state important?
  5. When should workflow steps run in parallel?
  6. How should approval checkpoints be implemented?
  7. Why are retries dangerous for write operations?
  8. How would you measure end-to-end workflow reliability?

Reflection: If every individual AI step succeeds but the overall workflow performs an unauthorized action, has the system succeeded? What does this reveal about orchestration quality?

12. Active Connections

Coming next — #011: Agent Evaluation: Measuring Whether AI Workflows Actually Succeed.

13. References and Further Reading

  1. LangGraph — Overview
  2. OpenAI Agents SDK — Documentation
  3. Microsoft Agent Framework — Documentation
  4. Temporal — Durable Execution Documentation
  5. Model Context Protocol — Official Documentation

Framework capabilities and implementation guidance evolve. Verify the current documentation when building production systems.


Final Takeaway

A reliable AI workflow is not defined by how many agents or tools it uses. It is defined by whether it coordinates work correctly, handles failures, respects controls, and delivers a verified outcome.

AI Engineering — Active Concepts & Practices
Active Concept #010 — Agent Orchestration

AIYING — Accomplishing with AI

Understand → Connect → Apply → Accomplish

AI Engineering Active Concepts #009 — Model Context Protocol (MCP): Connecting AI to Tools and Data

AI ENGINEERING — ACTIVE CONCEPTS & PRACTICES | #009

Model Context Protocol (MCP): Standardizing AI Connections to Tools and Data



Chapter 2: Engineering AI Applications and Agents

AIYING — Accomplishing with AI

The Big Idea: Tool calling enables AI applications to use external capabilities. Model Context Protocol (MCP) provides a common interface through which compatible AI applications can discover and interact with external tools, resources, and prompts.

Engineering question: How can an organization make its existing systems accessible to multiple AI applications without building and maintaining a separate custom integration for every combination?

Contents

  1. Why MCP Matters
  2. UNDERSTAND — What Is MCP?
  3. CONNECT — Related Engineering Concepts
  4. MCP Architecture and Lifecycle
  5. APPLY — Enterprise Procurement Integration
  6. Worked Example: Purchase Order Lookup
  7. Engineering Decisions and Trade-offs
  8. Active Industry Practices
  9. ACCOMPLISH — Design an MCP Integration
  10. Student and Practitioner Project
  11. Check Your Understanding
  12. Active Connections
  13. References and Further Reading

1. Why MCP Matters

Imagine an enterprise operating three AI applications:

  • A procurement assistant
  • A technical-support assistant
  • An AI operations assistant

Each application needs information from enterprise databases, document repositories, and business software.

Without a common integration approach, engineering teams may develop separate connectors for each application and external service.

This creates duplicated work, inconsistent interfaces, maintenance costs, and additional security review requirements.

MCP addresses part of this integration challenge by standardizing how AI applications discover and interact with exposed capabilities.

MCP standardizes the interface between compatible AI applications and external capabilities. It does not eliminate the need to implement, secure, and maintain the underlying integrations.

↑ Back to Contents

2. UNDERSTAND — What Is MCP?

Model Context Protocol (MCP) is an open protocol for connecting AI applications to external systems that provide tools, resources, and reusable prompts.

Originally introduced by Anthropic, MCP has developed as an ecosystem protocol with implementations across multiple AI platforms and developer tools.

The three architectural roles

ComponentResponsibility
MCP HostThe AI application that manages user interaction and MCP connections
MCP ClientA protocol component within the host that communicates with an MCP server
MCP ServerExposes capabilities through a standardized MCP interface

A host can manage connections to multiple servers through separate MCP clients.

The three foundational server capabilities

CapabilityPurposeExample
ToolsExpose callable operationsRetrieve a purchase order
ResourcesExpose contextual informationRead an approved supplier policy
PromptsExpose reusable prompt templatesSupplier delay analysis template

Tools, resources, and prompts are distinct protocol concepts. A server may expose one or more of them.

How is MCP different from an API?

An API defines how software accesses a particular service. MCP defines a common interface for presenting capabilities to compatible AI applications.

An MCP server can wrap an existing REST API, database, or enterprise service. The original API remains part of the implementation.

How is MCP different from tool calling?

Tool calling is the process through which a model or AI application requests an external operation.

MCP provides a standardized mechanism for discovering and accessing tools and other capabilities.

An AI application may translate a model-generated tool request into an MCP tool invocation.

Neither tool calling nor MCP automatically guarantees that an operation is safe or authorized.

↑ Back to Contents

3. CONNECT — Related Engineering Concepts

ConceptConnection to MCP
Tool CallingMCP tools can be made available for model-requested operations
Structured OutputsTool arguments and results use structured data
JSON SchemaDescribes tool input and output structures
APIsMCP servers can expose capabilities backed by APIs
Context EngineeringMCP resources can contribute external context
AI AgentsAgents may coordinate capabilities exposed by MCP servers
AuthenticationEstablishes identities and access credentials
AuthorizationDetermines which operations and records are permitted
ObservabilityMonitors server interactions, errors, and latency
AI GovernanceEstablishes trust, oversight, and accountability requirements

An important architectural insight

MCP separates the presentation of external capabilities from much of the application-specific integration code.

This can improve reuse and interoperability when both the host and server implement compatible protocol capabilities.

↑ Back to Contents

4. MCP Architecture and Lifecycle

Enterprise AI Assistant — MCP Host

↓

MCP Client

↓ Protocol Communication

MCP Server

↓

Enterprise API / Database / Service

↓

Authorized Result

↓

AI Application

Step 1 — Connection and initialization

The MCP client and server establish communication and negotiate supported protocol capabilities.

Step 2 — Capability discovery

The client can discover available tools, resources, or prompts using the relevant protocol operations.

Step 3 — Model or application selection

The host determines which available capability is relevant to the task. A model may propose a tool call, but application logic remains responsible for execution decisions.

Step 4 — Invocation

The MCP client sends a request to the server using the defined protocol interface.

Step 5 — External execution

The server may access an underlying API or database, subject to applicable permissions and controls.

Step 6 — Result handling

The result returns to the host, which may validate it, display it, or supply relevant information to the model.

Transport options

MCP supports communication arrangements including local standard input/output (stdio) and remote Streamable HTTP transport.

Transport selection affects deployment, authentication, operational monitoring, and security architecture.

Use the current MCP specification for implementation details because protocol features and transport guidance evolve.

↑ Back to Contents

5. APPLY — Enterprise Procurement Integration

Scenario: Multiple Assistants, Shared Enterprise Capabilities

A manufacturing company has purchase-order information in an ERP system, inventory records in a database, and supplier policies in a document repository.

The organization wants multiple AI assistants to access these capabilities through controlled interfaces.

Approach A — Separate integrations

Each assistant implements its own connection logic for the ERP system, inventory database, and document repository.

Changes to an underlying API may require updates across multiple applications.

Approach B — Shared MCP servers

The engineering team develops or deploys MCP servers that expose approved capabilities:

  • Procurement server: Purchase-order lookup tools.
  • Inventory server: Stock availability tools.
  • Policy server: Approved procurement documents as resources.

Compatible AI applications connect through MCP clients.

Server implementations still need to enforce user permissions, data restrictions, input validation, and operational controls.

Engineering outcome

This architecture may reduce duplicated integration work and improve reuse.

However, standardizing the interface does not automatically make business semantics, permissions, or error handling identical across systems.

↑ Back to Contents

6. Worked Example: Purchase Order Lookup

The following is a conceptual example using fictional enterprise data. It is not a live MCP connection.

Available MCP tool

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

Illustrative MCP tool request

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_purchase_order",
    "arguments": {
      "po_id": "PO-1048"
    }
  }
}

Illustrative tool result

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "PO-1048: delayed; revised delivery 2026-11-23"
      }
    ]
  }
}

The tool result is illustrative. Production implementations should use appropriate typed outputs, validation, error reporting, and access controls.

What happens next?

The AI assistant can report the retrieved order status.

If the user also requests a follow-up task, the host may make an additional authorized tool available for that purpose.

The MCP server must not assume that a request from an AI model is automatically permitted.

Key distinction

The model may select the capability. The MCP client transports the request. The server implements the operation. The application and supporting systems remain responsible for authorization and outcome verification.

↑ Back to Contents

7. Engineering Decisions and Trade-offs

DecisionPotential BenefitRisk or Trade-off
Shared MCP serversReusable integrationsShared dependency and operational concentration
Local serversConvenient local tool accessHost-machine access and process security risks
Remote serversCentralized servicesNetwork, authentication, and availability concerns
Read-only capabilitiesLower operational impactLimited automation
Write-enabled toolsGreater workflow automationHigher risk of unintended side effects
Broad tool catalogsMore capabilitiesSelection complexity and attack surface
Third-party serversFaster integrationSupply-chain and trust assessment requirements

Important security risks

  • Malicious or compromised MCP servers
  • Excessive tool permissions
  • Unauthorized access to enterprise records
  • Prompt injection through tool results or resources
  • Credential leakage or insecure token handling
  • Unapproved data transmission
  • Misleading tool descriptions
  • Unintended or repeated write operations

Recommended engineering controls

  • Maintain an approved server inventory.
  • Review server provenance and implementation.
  • Use least-privilege credentials.
  • Enforce authorization for each sensitive operation.
  • Validate tool inputs and outputs.
  • Require appropriate approval for consequential actions.
  • Restrict access to sensitive resources.
  • Log relevant operations without exposing secrets.
  • Monitor errors, changes, and unusual tool activity.
  • Test resilience and failure recovery.
MCP standardizes connectivity. Security, trust, and governance must still be engineered around every connection.

↑ Back to Contents

8. Active Industry Practices

Established foundations

  • Client-server protocol architecture
  • Structured tool discovery and invocation
  • Resource access through standardized interfaces
  • Reusable prompt templates
  • Local and remote server deployments
  • Integration with existing APIs and services

Developing engineering practices

  • Enterprise MCP server registries
  • Centralized server governance
  • Fine-grained tool access policies
  • Multi-server agent architectures
  • Server trust and provenance assessment
  • MCP observability and evaluation

Where MCP is relevant

MCP is relevant to AI coding assistants, enterprise knowledge assistants, data-analysis workflows, business-process automation, agentic applications, and AI-enabled developer environments.

It is particularly useful when multiple compatible AI applications need reusable access to external capabilities.

For a simple application with one stable API integration, a direct API connection may remain the more practical engineering choice.

Practice status: Open integration protocol with an evolving ecosystem and operational practices.

Reviewed: November 2026.

↑ Back to Contents

9. ACCOMPLISH — Design an MCP Integration

Exercise: Enterprise Procurement MCP Architecture

Consider a fictional manufacturing company with the following systems:

ERP: Purchase orders and supplier records.

Inventory database: Stock availability.

Document repository: Procurement policies.

AI applications: Procurement assistant and operations assistant.

Your tasks

  1. Identify the capabilities each AI application needs.
  2. Decide which capabilities should be tools and which should be resources.
  3. Design an MCP server architecture.
  4. Define a purchase-order lookup tool and its input schema.
  5. Specify how user permissions should be enforced.
  6. Identify operations requiring approval.
  7. Describe how errors and unavailable services should be handled.
  8. Explain how the design reduces duplicated integrations.

Reusable AI-assisted prompt

Act as an enterprise AI integration engineer.

Design an MCP-based architecture for a
fictional procurement organization.

Systems:
- ERP purchase orders
- Inventory database
- Procurement policy repository

AI applications:
- Procurement assistant
- Operations assistant

Provide:
1. MCP host, client, and server roles.
2. Proposed tools, resources, and prompts.
3. Tool input schemas.
4. Capability discovery and execution flow.
5. Authentication and authorization controls.
6. Human approval requirements.
7. Failure handling and observability.
8. Integration reuse benefits.
9. Risks and limitations.
10. A small implementation test plan.

Do not assume that MCP automatically
provides security or business authorization.

Accomplishment: Design an MCP integration architecture that supports reusable capabilities while preserving operational control.

↑ Back to Contents

10. Student and Practitioner Project

Mini Project: Build a Read-Only MCP Server

Objective: Build or prototype an MCP server that exposes purchase-order lookup capabilities using fictional data.

Project requirements

  1. Create a small fictional purchase-order dataset.
  2. Choose a compatible MCP SDK.
  3. Implement a read-only purchase-order lookup tool.
  4. Define and validate tool input parameters.
  5. Expose a sample procurement-policy resource.
  6. Connect using a compatible MCP client or inspection tool.
  7. Test capability discovery.
  8. Test successful and unsuccessful tool invocations.
  9. Check that unauthorized or invalid requests are rejected.
  10. Document execution logs and observed limitations.

Suggested evaluation measures

MetricWhat It Measures
Discovery successWhether the client can discover capabilities
Invocation accuracyWhether valid tool calls return correct results
Input validationWhether invalid arguments are rejected
Access controlWhether unauthorized operations are blocked
LatencyTime required to complete tool requests
Error handlingWhether failures are reported accurately
Reuse potentialWhether multiple compatible clients can use the server

Deliverable: A working demonstration or architecture prototype, tool definition, sample request and response, test results, and an engineering recommendation.

Use fictional data and a local development environment. Do not expose real credentials or production systems during the exercise.

↑ Back to Contents

11. Check Your Understanding

  1. What problem does MCP address in AI engineering?
  2. What is the difference between an MCP host, client, and server?
  3. How do MCP tools differ from resources and prompts?
  4. How is MCP different from a conventional API?
  5. How does MCP relate to model tool calling?
  6. Does MCP automatically enforce enterprise authorization?
  7. What risks arise from connecting untrusted MCP servers?
  8. When might a direct API integration be preferable?

Reflection: If an MCP server exposes a tool named "approve_payment", should an AI assistant be allowed to invoke it merely because the tool is discoverable? What additional controls are necessary?

↑ Back to Contents

12. Active Connections

Coming next — #010: Agent Orchestration: Designing Reliable Multi-Step AI Workflows.

↑ Back to Contents

13. References and Further Reading

  1. Model Context Protocol — Introduction
  2. MCP — Official Specification
  3. MCP — Documentation and Developer Guides
  4. MCP — Official GitHub Organization
  5. MCP — Security Best Practices

MCP specifications, SDKs, transport guidance, and security practices evolve. Consult the latest official documentation before implementing production integrations.


Final Takeaway

MCP helps make external tools, data, and reusable prompts accessible through a common protocol. Effective AI engineering combines this interoperability with explicit security, authorization, validation, and operational accountability.

AI Engineering — Active Concepts & Practices
Active Concept #009 — Model Context Protocol

AIYING — Accomplishing with AI

Understand → Connect → Apply → Accomplish

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 — Living Glossary #018 | Structured Outputs: Making AI Responses Machine-Readable and Verifiable

AI Engineering — Living Glossary #018

Lesson 18 | Chapter 3 Finale

Structured Outputs



Making AI Responses Machine-Readable and Verifiable

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

Understand the Term. Connect the Technology. Apply the Knowledge.

The Problem: A Correct Answer That Breaks the System

An accounts-payable team introduces an AI assistant to extract information from supplier invoices. The assistant reads an invoice and replies:

The invoice is from Northstar Components. It is for ₹48,500 and is due on 30 November 2026.

The answer looks useful to a human. But the accounting application expects an invoice number, supplier identifier, amount as a number, currency code, and due date in a specific format.

A human can interpret the response. Software should not have to guess where one field ends and another begins.

The engineer therefore changes the design: the AI must return data that conforms to a predefined schema.

Engineering insight: Generating the right words and generating a reliable software interface are different tasks.
↑ Back to contents

1. What Are Structured Outputs?

Structured outputs are AI-generated responses required to follow a defined data structure, typically specified using a schema.

Instead of producing unrestricted prose, the model produces data that an application can parse and validate.

Common representations include JSON objects, typed records, arrays, enumerated values, and other machine-readable formats.

Example

{ "invoice_number": "INV-2048", "supplier": "Northstar Components", "amount": 48500.00, "currency": "INR", "due_date": "2026-11-30", "requires_review": false }

The response now contains named fields, predictable data types, and a standardized date.

However, a valid structure does not prove that the invoice number, amount, or date was extracted correctly.

Critical distinction: Schema validity is not factual accuracy. Both must be checked separately.
↑ Back to contents

2. Why AI Engineers Need Structured Outputs

AI engineering increasingly involves connecting language models to conventional software systems. These systems expect predictable interfaces.

  • Integration: Applications can consume named fields without interpreting prose.
  • Automation: Workflows can route cases using explicit classifications and values.
  • Validation: Programs can reject missing, malformed, or unexpected data.
  • Testing: Outputs can be compared against known reference records.
  • Observability: Engineers can track failures by field and schema version.
  • Governance: Data contracts make downstream responsibilities clearer.

Structured outputs are especially valuable when an AI response triggers another system, creates a database record, or informs a consequential decision.

↑ Back to contents

3. Understanding the Data Contract

A schema defines the shape and constraints of expected data.

It can specify field names, data types, required properties, allowed values, nested objects, and restrictions on additional fields.

Illustrative JSON Schema

{ "type": "object", "properties": { "invoice_number": { "type": "string" }, "amount": { "type": "number" }, "currency": { "type": "string", "enum": ["INR", "USD", "EUR"] }, "due_date": { "type": ["string", "null"] }, "requires_review": { "type": "boolean" } }, "required": [ "invoice_number", "amount", "currency", "due_date", "requires_review" ], "additionalProperties": false }

This schema requires every listed field, restricts the currency to three codes, and prevents undeclared properties.

The due date is nullable because the source document may not contain one. A production application should also validate its date format.

Different model providers support different subsets of JSON Schema. The schema must be designed for the selected API's supported structured-output mode.

Design principle: The schema is an interface contract, not a substitute for business rules.
↑ Back to contents

4. How Structured Outputs Work

Step 1 — Define: The application defines its required schema.

Step 2 — Request: The application supplies the task, source content, and output contract to the model.

Step 3 — Generate: The model produces a structured response. Supported constrained-generation modes can restrict the possible output format.

Step 4 — Validate: Application code checks the output against the schema and business constraints.

Step 5 — Verify: Relevant values are checked against source evidence or authoritative records.

Step 6 — Act: The application accepts, rejects, retries, or escalates the result.

A production implementation must also handle refusals, incomplete responses, timeouts, unsupported schemas, and API-specific failure conditions.

The application—not the language model— ultimately decides whether the output is acceptable for downstream use.

↑ Back to contents

5. Approaches and Implementation Patterns

A. Prompt-Only Formatting

The prompt asks the model to return JSON. This is easy to prototype but does not provide a strong structural guarantee.

B. JSON-Format Mode

Some APIs provide a mode intended to produce syntactically valid JSON. Valid JSON alone does not guarantee the required fields or types.

C. Schema-Constrained Generation

Supported APIs can constrain generation to match a supplied schema or supported schema subset. This offers stronger structural reliability than instructions alone.

D. Application-Side Validation

The application parses and validates the returned object, regardless of the model's generation mode.

E. Validate, Repair, or Escalate

Invalid results can trigger a bounded retry, a correction request, a fallback workflow, or human review.

Repeated retries should not be unlimited: they increase cost and latency without guaranteeing correctness.

↑ Back to contents

6. Structured Outputs vs. Related Concepts

Concept Main Purpose Key Distinction
Prompt Engineering Guide model behavior Instructions alone do not enforce a schema
JSON Mode Produce JSON syntax Valid JSON may violate the expected schema
Structured Outputs Conform to a data contract Focuses on predictable response structure
Tool Calling Propose an external operation Tool arguments can be structured, but execution is separate
Guardrails Constrain unsafe or invalid behavior Schema checks cover only part of the risk
Grounding Connect claims to evidence Addresses factual support, not merely formatting

A model can return perfectly valid JSON containing an incorrect invoice total. Conversely, a factually correct explanation may be impossible for an application to parse.

Reliable systems need both structural correctness and factual verification.

↑ Back to contents

7. Production Architecture

Source Document | v Document Extraction / OCR | v AI Model + Output Schema | v Structured Response | v Schema Validator | v Business Rule Validator | v Source / Record Verification | +---- Failure ----> Retry or Review | v Authorized Application Action | v Audit Log and Monitoring

This architecture separates generation, validation, verification, authorization, and execution.

It also makes failures easier to diagnose: a parsing error is different from an incorrect extracted value or an unauthorized downstream action.

↑ Back to contents

8. Reliability, Safety, and Security

Schema Validity

Check field presence, data types, enumerations, nesting, and unexpected keys.

Semantic Validity

Check whether values make sense. An invoice amount cannot be negative unless the supported document type permits credits or adjustments.

Evidence Verification

Compare extracted values with the original document or trusted systems. A model's confidence claim is not independent evidence.

Prompt Injection

Documents may contain instructions attempting to influence the model. Treat document text as untrusted data, not as authority to change the workflow.

Authorization

Even valid structured data must not automatically authorize payments, record changes, or external communication.

Operational Controls

  • Set maximum retry counts and timeouts.
  • Version schemas and record compatibility changes.
  • Use least-privilege access for downstream systems.
  • Log validation outcomes without unnecessarily exposing sensitive data.
  • Escalate ambiguous or high-risk cases.
Remember: A valid JSON object is not a security approval, a factual guarantee, or permission to execute an action.
↑ Back to contents

9. Industry Applications

Industry Structured Output Downstream Use
Finance Invoice fields Validation and payment review
Customer Support Category, priority, summary Ticket routing
Manufacturing Defect classification Quality workflow
Healthcare Administration Document metadata Administrative processing with appropriate controls
Cybersecurity Alert indicators and severity Analyst triage
Human Resources Application metadata Administrative organization and review

The recurring pattern is the same: language understanding is converted into a predictable software interface.

↑ Back to contents

10. Industry Case: Invoice Processing

Illustrative enterprise scenario, not a claim about a specific company.

The Business Problem

A company receives thousands of supplier invoices in different layouts. Manual entry is slow, while ordinary OCR provides text without always identifying business meaning.

The Proposed AI System

  1. Receive a supplier invoice.
  2. Extract text and document layout information.
  3. Ask the model for fields matching an invoice schema.
  4. Validate the returned structure.
  5. Check arithmetic and required business fields.
  6. Match supplier and purchase-order information.
  7. Route mismatches to a human reviewer.
  8. Submit approved records to the accounting system.

Example Exception

The invoice states a total of ₹48,500. The model returns the same amount, but the purchase order authorizes ₹45,800.

The structured response is valid. The extracted amount may also be accurate. Nevertheless, the transaction should be flagged because it does not match the purchasing record.

What the Engineer Learns

Structural correctness, extraction accuracy, business eligibility, and execution authorization are separate decisions.

Case insight: Structured outputs make exceptions detectable; they do not eliminate the need to investigate exceptions.
↑ Back to contents

11. Engineering Design Decisions

Before implementing structured outputs, the engineer must decide:

  1. Which fields are genuinely required by downstream applications?
  2. Should an unknown value be null, omitted, or an explicit status?
  3. Which fields require controlled enumerations?
  4. Which constraints belong in the schema versus business validation?
  5. What happens when the model refuses, times out, or returns incomplete data?
  6. When is retry appropriate, and when should the system escalate?
  7. How will schema versions be managed across multiple consuming services?
  8. Which actions require human approval?

A good schema should be sufficiently precise for dependable integration without forcing the model to invent information that the source does not contain.

↑ Back to contents

12. Hands-On Mini-Project

Build a Structured Support-Ticket Classifier

Objective: Convert an unstructured customer message into a validated support record.

Input

I cannot sign in to my account after resetting my password. I need access before tomorrow's client meeting.

Required Output

{ "category": "access", "priority": "high", "summary": "User cannot sign in after password reset", "needs_human_review": false }

This is an illustrative expected result. The actual priority must follow a documented support policy.

Student Tasks

  1. Define a schema with category, priority, summary, and needs_human_review.
  2. Restrict category to access, billing, technical, or other.
  3. Restrict priority to low, medium, or high.
  4. Submit at least 20 varied test messages to an AI model.
  5. Validate each output with a JSON Schema validator.
  6. Compare the classification with human-reviewed expected labels.
  7. Record failures and improve the schema or instructions.

Python Validation Example

The following example validates a response already received from a model. It does not make a model API call.

# Install once: # pip install jsonschema from jsonschema import validate, ValidationError schema = { "type": "object", "properties": { "category": { "type": "string", "enum": [ "access", "billing", "technical", "other" ] }, "priority": { "type": "string", "enum": ["low", "medium", "high"] }, "summary": { "type": "string", "minLength": 1 }, "needs_human_review": { "type": "boolean" } }, "required": [ "category", "priority", "summary", "needs_human_review" ], "additionalProperties": False } result = { "category": "access", "priority": "high", "summary": "Cannot sign in after reset", "needs_human_review": False } try: validate(instance=result, schema=schema) print("Schema valid") except ValidationError as error: print("Schema invalid:", error.message)

Extend the project by rejecting empty summaries, checking ticket categories against policy, and routing uncertain classifications to review.

↑ Back to contents

13. Evaluation and Acceptance Criteria

Metric What It Measures Illustrative Target
Schema compliance Percentage passing schema validation 100% before downstream acceptance
Category accuracy Agreement with reviewed labels At least 90% in the exercise
Priority accuracy Agreement with defined policy At least 90% in the exercise
Escalation recall Fraction of review-required cases flagged 100% for designated critical test cases
Retry rate Fraction requiring another attempt Measure and minimize
Latency Time to a validated result Set according to application needs

These are learning targets, not universal production benchmarks. A real deployment requires larger representative datasets, failure analysis, and risk-based thresholds.

The student should report results separately for syntax, schema compliance, classification quality, and business-rule compliance.

↑ Back to contents

14. Connected Living Glossary Terms

↑ Back to contents

15. Living Update

Structured-output capabilities continue to evolve across AI platforms. Engineers should periodically review:

  • Supported schema features and restrictions.
  • Constrained-generation guarantees.
  • Handling of refusals and incomplete responses.
  • Streaming behavior and partial results.
  • SDK validation and parsing capabilities.
  • Compatibility with tool calling and agent systems.

Update discipline: Test schema behavior against the actual model and API version used in production. Do not assume that a provider's entire JSON Schema specification is supported.

↑ Back to contents

16. Key Takeaway and One Action

Understand the Term: Structured outputs require AI responses to follow a defined data contract.

Connect the Technology: Schemas connect language-model generation to conventional software systems.

Apply the Knowledge: Validate the structure, verify the facts, and authorize actions separately.

One Action: Take one AI task that currently returns prose. Design a schema, test 20 examples, and measure the failure rate.

A well-formed response is ready to be checked—not automatically ready to be trusted.

↑ Back to contents

17. References and Further Learning

  1. JSON Schema — Official Documentation
  2. OpenAI — Structured Outputs
  3. Anthropic — Developer Documentation
  4. OWASP — Top 10 for LLM Applications
  5. NIST — AI Risk Management Framework
  6. Python jsonschema — Documentation
↑ Back to contents

AIYING — Accomplishing with AI

The Language of AI Engineering
The Terms AI Engineers Must Truly Understand

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

Living Glossary #018 | Chapter 3 Complete | Lesson 18 of 24

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